2011-08-28 50 views
6

我发现与NumPy的一个ndarray以下令人费解的行为和一个自定义的D型细胞,当数组赋值问题:NumPy的:使用自定义的D型

import numpy as np 

# Make a custom dtype with a single triplet of floats (my actual dtype has other 
# components, but this suffices to demonstrate the problem. 
dt = np.dtype([('a', np.float64, 3)]) 

# Make a zero array with this dtype: 
points = np.zeros((4, 4), dtype=dt) 

# Try to edit an entry: 
points[0][0]['a'] = np.array([1, 1, 1]) 

print points[0][0]['a'] 

现在,这回来为含有不[1。如我所料,但是[1]。 0. 0],只在第一个坐标上执行赋值。我可以通过坐标明智地执行分配来解决这个问题,但这看起来没有必要,因为在这种情况下完全分配肯定应该是默认行为。

想到这里发生了什么?

回答

2

有分配的点数多的方法,如果你希望你的方法工作:

points[0][0]['a'][:] = np.array([1, 1, 1]) 

或:

points[0,0]['a'][:] = np.array([1, 1, 1]) 

因为点[0,0] [ '一']是一个数组,如果你想改变数组的内容,你应该使用索引。

+0

正是我在找的,谢谢。 –

3

如果您更改索引的排序,如下所示:points['a'][0][0] = np.array([1, 1, 1]),它对我来说可行(在Ubuntu 10.04上,python 2.6.5,numpy 1.3.0)。我希望我知道为什么。

+0

也适用于我。虽然我真的想做的事情会是这样的: p = points [0] [0] p ['a'] = np.array([1,1,1]) 和其他操作如果有必要的话。 –

+0

@Tim:AFAIK,首先指定命名列似乎很自然,然后才去数字索引。因此,写作点['a'] [0]或点[0] ['a'](适用于dtype-ed POD阵列)的能力就像是免费的午餐。 –