将记录数组存储在对象数组中

时间:2010-04-14 23:15:46

标签: python numpy

我想将记录数组列表 - dtype is(uint32,float32) - 转换为dtype np.object的numpy数组:

X = np.array(instances, dtype = np.object)

其中instances是数据类型为np.dtype([('f0', '<u4'), ('f1', '<f4')])的数组列表。 但是,上面的语句会生成一个数组,其元素的类型也是np.object

X[0]
array([(67111L, 1.0), (104242L, 1.0)], dtype=object)

有人知道为什么吗?

以下陈述应与上述陈述相同,但会给出所需的结果:

X = np.empty((len(instances),), dtype = np.object)
X[:] = instances
X[0]
array([(67111L, 1.0), (104242L, 1.0), dtype=[('f0', '<u4'), ('f1', '<f4')])

谢谢&amp;最好的祝福,  彼得

1 个答案:

答案 0 :(得分:1)

Stéfanvander Walt(一位笨拙的开发者)explains

  

ndarray构造函数尽力而为   猜猜你是什么类型的数据   喂它,但有时它需要一个   一点帮助......

     

我更喜欢构造数组   显然,所以毫无疑问是什么   发生在引擎盖下:

当你说

之类的话
instance1=np.array([(67111L,1.0),(104242L,1.0)],dtype=np.dtype([('f0', '<u4'), ('f1', '<f4')]))
instance2=np.array([(67112L,2.0),(104243L,2.0)],dtype=np.dtype([('f0', '<u4'), ('f1', '<f4')]))
instances=[instance1,instance2]
Y=np.array(instances, dtype = np.object)

np.array被迫猜测你想要的数组的维数是多少。 instances是两个对象的列表,每个对象的长度为2.因此,非常合理地np.array猜测Y应该具有形状(2,2):

print(Y.shape)
# (2, 2)

在大多数情况下,我认为这是理想的。然而, 在你的情况下,因为这不是你想要的,你必须明确地构造数组:

X=np.empty((len(instances),), dtype = np.object)
print(X.shape)
# (2,)

现在毫无疑问X的形状:(2, ),所以当您输入数据时

X[:] = instances

numpy非常聪明,可以将instances视为两个对象的序列。