NumPy:使用自定义数据类型时的数组赋值问题

6
我发现使用NumPy和自定义ndarray dtype时出现以下令人困惑的行为:
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. 1.],而是 [1. 0. 0.],只对第一个坐标进行了赋值。我可以通过逐个坐标进行赋值来解决这个问题,但考虑到完全赋值应该是默认行为,这样做似乎是不必要的。
您对此有什么想法?
2个回答

3
如果你改变索引的顺序,像这样:points['a'][0][0] = np.array([1, 1, 1]),对我而言是可以正常工作的(在Ubuntu 10.04上,使用Python 2.6.5和Numpy 1.3.0)。但我不知道原因。

我也试过了。不过我真正想做的是像这样: p = points[0][0] p['a'] = np.array([1, 1, 1]) 如果需要的话,还可以对p进行其他操作。 - Tim Kunisky
@Tim:据我所知,首先指定命名列,然后再使用数字索引似乎是很自然的。因此,能够编写points['a'][0]或points[0]['a'](对于POD类型的数组有效)感觉就像是免费的午餐。 - ev-br

2

有很多方法可以分配点数,如果你想让你的方法有效:

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

或者:

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接