numpy:无法建立二维数组的元组 [英] Numpy : can't build a 2-D array of tuples
问题描述
我遇到了numpy的数组构造函数的问题.我想用元组初始化一个二维数组,但是它不能像整数一样工作:
I've a problem with numpy's array constructor. I want to initialize an 2-D array with tuples, but it doesn't work as with integers :
>>> A = array([[0, 0], [3, 5]])
>>> print(A)
[[0 0]
[3 5]]
>>> A[1, 1] = 7
>>> print(A)
[[0 0]
[3 7]]
>>> A = array([[(0, 0), (0, 1)], [(1, 0), None]], dtype=object)
>>> A[1, 1] = (2, 3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: invalid index
>>> A.shape
(2,)
我真的需要手动"填写这些矩阵.有什么主意吗?
I really need to fill these matrix "by hand". Any idea ?
推荐答案
您的代码似乎对我有用(使用显式numpy命名空间).我正在使用numpy v1.6.1:
Your code seems to work for me (using the explicit numpy namespace). I'm using numpy v1.6.1:
In [8]: import numpy as np
In [9]: A = np.array([[(0, 0), (0, 1)], [(1, 0), None]], dtype=object)
In [10]: A[1, 1] = (2, 3)
In [11]: A.shape
Out[11]: (2, 2)
In [12]: A
Out[12]:
array([[(0, 0), (0, 1)],
[(1, 0), (2, 3)]], dtype=object)
您使用的是什么版本的numpy?
What version of numpy are you using?
更新这似乎是与numpy版本相关的问题,因为我可以使用numpy v1.5.1(OSX Lion中基本python安装附带的版本)重现OP的错误.我不确定这是否是numpy中的错误,该错误已修复或实现中的更改.我要么更新到numpy的较新版本,要么使用以下简单的解决方法:
Update This seems to be an issue related to the numpy version since I can reproduce the OP's error using numpy v1.5.1 (the version that comes packaged with the base python install in OSX Lion). I'm not sure if this was a bug in numpy that was fixed or a change in the implementation. I would either update to a newer version of numpy or use this simple workaround:
>>> A = np.array([[(0, 0), (0, 1)], [(1, 0), None]], dtype=object)
>>> A[1][1] = (2,3)
>>> A
array([[(0, 0), (0, 1)], [(1, 0), (2, 3)]], dtype=object)
更新#2 这是一个常规修补程序,希望您可以适应:
Update #2 Here's a general fix that hopefully you can adapt:
>>> C = np.empty((2,2),object)
>>> B = [[(0, 0), (0, 1)], [(1, 0), None]]
>>> C[:] = B
>>> C
array([[(0, 0), (0, 1)],
[(1, 0), None]], dtype=object)
>>> C.shape
(2, 2)
>>> C[1,1] = (2,3)
>>> C
array([[(0, 0), (0, 1)],
[(1, 0), (2, 3)]], dtype=object)
这篇关于numpy:无法建立二维数组的元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!