在异构阵列numpy的数组操作 [英] Array operations on heterogeneous numpy arrays
问题描述
我需要一个有效的异构阵列,其中第一个元素是一个int,其余均为浮动。创建后,但是,基本的数组操作是爆炸。
A = np.zeros(1 DTYPE = 0-14,F4,F4')
B = np.array([3,3,3])
A + B
类型错误:无效的类型提升
通过结构化数组这个样子,这在田野呼吁迭代操作一般不工作。
即使加入 A
本身不工作:
在[476]:A = np.zeros(1 DTYPE = 0-14,F4,F4')在[477]:A + A
...
类型错误:ufunc加不包含循环使用签名匹配的类型DTYPE([('F0','< 0-14'),('F1','< F4'),('F2','< F4')])......
在换句话说,有增加的一种方式的 INT
到 INT
,一个浮动
到 INT
,而不是加入 A
元素到另一个的方式元素。
A
的一个元素是元组
或 numpy.void
(取决于你如何访问它)
在[478]:A.item()
出[478]:(0,0.0,0.0)在[479]:类型(A.item())
出[479]元组在[480]:类型(A [0])
出[480]:numpy.void
要跨越一个结构化的阵列通常必须遍历字段名的字段。
在[493]:B = np.arange(3)在[494]:因为我在历数(A.dtype.names)名称:
A [名] = A [名] + B [I]
.....:在[495]:一
出[495]:
阵列([(0,1.0,2.0)],
DTYPE = [('F0','&下; 6-14'),(F1,&所述; F4'),('F2','&所述; F4')])
如果所有字段有相同的类型,例如 DTYPE ='0-14,0-14,6-14'
,则有可能以查看结构化阵列作为均相DTYPE,并在其上执行常规的数学。但随着你的花车和整数的组合,这是不可能的。
I need an efficient heterogeneous array in which the first element is an int and the rest are floats. After creating it, however, basic array operations are exploding.
A = np.zeros(1, dtype='i4, f4, f4')
B = np.array([3,3,3])
A + B
TypeError: invalid type promotion
With a structured array like this, operations that call for iteration over the fields generally don't work.
Even adding A
to itself does not work:
In [476]: A = np.zeros(1, dtype='i4, f4, f4')
In [477]: A+A
...
TypeError: ufunc 'add' did not contain a loop with signature matching types dtype([('f0', '<i4'), ('f1', '<f4'), ('f2', '<f4')]) ....
In other words, there's a way of adding an int
to an int
, a float
to an int
, but not a way of adding a A
element to another element.
An element of A
is a tuple
or a numpy.void
(depending on how you access it)
In [478]: A.item()
Out[478]: (0, 0.0, 0.0)
In [479]: type(A.item())
Out[479]: tuple
In [480]: type(A[0])
Out[480]: numpy.void
To work across the fields of a structured array you usually have to iterate over the field names.
In [493]: B=np.arange(3)
In [494]: for i,name in enumerate(A.dtype.names):
A[name] = A[name]+B[i]
.....:
In [495]: A
Out[495]:
array([(0, 1.0, 2.0)],
dtype=[('f0', '<i4'), ('f1', '<f4'), ('f2', '<f4')])
If all the fields have the same type, e.g. dtype='i4, i4, i4'
, then it is possible to view the structured array as a homogeneous dtype, and perform regular math on it. But with your mix of floats and ints, that isn't possible.
这篇关于在异构阵列numpy的数组操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!