简体   繁体   English

numpy:无法建立二维数组的元组

[英]Numpy : can't build a 2-D array of tuples

I've a problem with numpy's array constructor. 我对numpy的数组构造函数有问题。 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 ? 任何想法 ?

Your code seems to work for me (using the explicit numpy namespace). 您的代码似乎对我有用(使用显式的numpy命名空间)。 I'm using numpy v1.6.1: 我正在使用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)

What version of numpy are you using? 你使用的是什么版本的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). 更新这似乎是一个与numpy版本相关的问题,因为我可以使用numpy v1.5.1(在OSX Lion中随基本python安装打包的版本)重现OP的错误。 I'm not sure if this was a bug in numpy that was fixed or a change in the implementation. 我不确定这是不是numpy中的错误已修复或实现中的更改。 I would either update to a newer version of numpy or use this simple workaround: 我会更新到更新版本的numpy或使用这个简单的解决方法:

>>> 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)

Update #2 Here's a general fix that hopefully you can adapt: 更新#2这是一个常规修复程序,希望您可以适应:

>>> 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM