np.abs能否获取dtype=[('real','<f8'),('ima

  • 本文关键字:abs f8 ima real np 获取 dtype python numpy
  • 更新时间 :
  • 英文 :


我正在尝试将一些代码从MATLAB移植到Python。MATLAB使用abs(数据(来获得数据中复数的绝对值。我使用h5py模块将其放入ndarray(dim - (151402, 16, 64))中。这个数组包含实数和imag值,我想计算它们的绝对值。Numpy文档表明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'), ('imag', '<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,其中包含单独的realimag字段。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, -0.2), dtype=[('real', '<f8'), ('imag', '<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'), ('imag', '<f8')]) -> dtype([('real', '<f8'), ('imag', '<f8')])

转换为复杂数据类型:

In [27]: np.abs(y['real']+y['imag']*1j)
Out[27]: 1.118033988749895

或者,我们可以使用view来转换数据类型:

In [28]: y.view('complex')
Out[28]: array(1.1-0.2j)
In [29]: np.abs(y.view('complex'))
Out[29]: 1.118033988749895

view并不总是适用于复合数据类型,但这里的底层数据字节布局是相同的。

相关内容

最新更新