2
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.

2
  • Please don't use list as a variable name. Commented Dec 24, 2010 at 0:15
  • oh sorry i was using "list" in my native language and when i translated it i didn't even realize it Commented Dec 24, 2010 at 0:17

3 Answers 3

3

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]])
Sign up to request clarification or add additional context in comments.

2 Comments

@pnodbnda Numpy only supports rectangular (NxM) arrays. Yours is not rectangular as the lower-right element is missing.
also, the data in an array must be homogeneous. if your element types are list and int, that's not homogeneous. if you changed the dtype to py_object it would work because they'd be of the homogeneous type object. that's the fundamental distinction -- lists are inhomogeneous, arrays are homogeneous. if you want to store inhomogeneous data types, use a list.
0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.