如何解决np.abs是否可以采用dtype = ['real','<f8','imag','<f8']]的输入数组并给出绝对值?
我正在尝试将一些代码从MATLAB移植到Python。 MATLAB使用abs(data)来获取数据中复数的绝对值。我使用h5py模块将其放入ndarray(dim - (151402,16,64))
中。该数组包含实和imag值,我想为其计算绝对值。大量的文档显示np.abs
是它的函数,但是在此ndarray上使用时,我得到了
error --> `numpy.core._exceptions.UFuncTypeError: ufunc 'absolute' did
not contain a loop with signature matching types
dtype([('real','<f8'),('imag','<f8')]) -> dtype([('real','<f8')])`.
这是否意味着np.abs无法为此数据计算绝对值?
解决方法
对于复杂的dtype数组,np.abs
会产生幅度,如其文档中所述:
In [18]: x= np.array(1.1 - 0.2j)
In [19]: x
Out[19]: array(1.1-0.2j)
In [20]: x.dtype
Out[20]: dtype('complex128')
In [21]: np.abs(x)
Out[21]: 1.118033988749895
但是您已经将复杂数组构造(或加载)为structured array
,并具有单独的real
和imag
字段。没有为np.abs
定义compound dtype
(大多数计算/ ufunc不适用于结构化数组)。
In [23]: dt = np.dtype([('real','<f8'),('imag','<f8')])
In [24]: y = np.array((1.1,-0.2),dt)
In [25]: y
Out[25]: array((1.1,dtype=[('real','<f8')])
In [26]: np.abs(y)
Traceback (most recent call last):
File "<ipython-input-26-e2973663f413>",line 1,in <module>
np.abs(y)
UFuncTypeError: ufunc 'absolute' did not contain a loop with signature matching types dtype([('real','<f8')]) -> dtype([('real','<f8')])
转换为复杂的dtype:
In [27]: np.abs(y['real']+y['imag']*1j)
Out[27]: 1.118033988749895
或者,我们可以使用view
来转换dtype:
In [28]: y.view('complex')
Out[28]: array(1.1-0.2j)
In [29]: np.abs(y.view('complex'))
Out[29]: 1.118033988749895
view
并不总是与复合dtypes一起使用,但是这里的底层数据字节布局是相同的。