NumPy:使用自定义数据类型时的数组赋值问题
我发现了一个关于NumPy和自定义数据类型在ndarray中的奇怪行为:
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])
,在我这边是可以正常工作的(我用的是Python 2.6.5和numpy 1.3.0,操作系统是Ubuntu 10.04)。我真希望我知道这是为什么。
2
有很多方法可以给点数赋值,如果你想让你的方法有效:
points[0][0]['a'][:] = np.array([1, 1, 1])
或者:
points[0,0]['a'][:] = np.array([1, 1, 1])
因为 points[0,0]['a'] 是一个数组,如果你想改变这个数组的内容,你应该使用索引。