Reputation: 659
from numpy import array
test_list = [[1,2],3]
x = array(test_list) #ValueError: setting an array element with a sequence.
Basically, I have a point with 2 coordinates and a scale and I was trying to put several on a ndarray but I can't do it right now. I could just use [1,2,3] but I'm curious about why I can't store that type of list in an array.
Upvotes: 2
Views: 4264
Reputation: 1821
If you really need non-rectangular arrays, you can give awkward
a try:
In [1]: import awkward
In [2]: test_list = [[1,2],3]
In [3]: x = awkward.fromiter(test_list)
In [4]: x
Out[4]: <UnionArray [[1 2] 3] at 0x7f69c087c390>
In [5]: x + 1
Out[5]: <UnionArray [[2 3] 4] at 0x7f69c08075c0>
In [6]: x[0]
Out[6]: array([1, 2])
In [7]: x[0, 1]
Out[7]: 2
It behaves in many ways like a numpy
array.
Upvotes: 0
Reputation: 9703
You can do
x = array([[1,2],3], dtype=object_)
which gives you a an array with a generic "object" dtype. But that doesn't get you very far. Even if you did
x = array([array([1,2]),3], dtype=object_)
you would have x[0] be an array, but you still couldn't index x[0,0], you'd have to do x[0][0].
It's a shame; there are places where it would be useful to do things like this and then do x.sum(1) and get [3, 3] as the result. (You can always do map(sum, x).)
Upvotes: -1
Reputation: 138347
It's failing because the array is non-rectangular. If we change the 3
to [3, 4]
then it works.
>>> array([[1, 2], [3, 4]])
array([[1, 2],
[3, 4]])
Upvotes: 3