0

I'm looking to create a numpy array of lists and define the first element in each list as a number in sequence.

So far I can create the numpy array of all the first elements but they are not nested within lists as I'd like.

So I have

 B=np.arange(1,10)
 Bnew = B.reshape((3,3))
 array([[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]])

but I want it to look like:

 array([[[1], [2], [3]],
        [[4], [5], [6]],
        [[7], [8], [9]]])

as I will be adding more numbers to each list component as I continue to modify the matrix.

Thanks!

2
  • Try reshape(3,3,1). Commented Feb 7, 2017 at 13:12
  • @Divakar the OP wants to be able to append to the innermost lists. Commented Feb 7, 2017 at 13:15

2 Answers 2

1

To be able to append to the cells of your array you need to make it dtype=object. You can force that using the following slightly ugly hack

a = [[i] for i in range(1, 10)]
swap = a[0]
a[0] = None # <-- this prevents the array factory from converting
            #     the innermost level of lists into an array dimension
b = np.array(a)
b[0] = swap
b.shape = 3, 3

now you can for example do

b[1,1].append(2)
b
array([[[1], [2], [3]],
       [[4], [5, 2], [6]],
       [[7], [8], [9]]], dtype=object)
Sign up to request clarification or add additional context in comments.

2 Comments

Paul, can you please explain why numpy converts the innermost dimension to an ndarray when the recipe clearly calls for it to be a List? I noticed that even specifying the dtype to object or np.object doesn't work. You really have to set some element to None (and then change it back). Is there a way to understand this behavior intuitively?
@Mathematician Wish I could. But, honestly, I don't think there is a good reason for not allowing the user more control on this. Maybe have a look here. It's a similar post but the people there are more knowledgable than I am.
0

What you want is a 3-dimensional numpy array. But reshape((3, 3)) will create a 2-dimensional array, because you are providing two dimensions to it. To create what you want, you should give a 3D shape to the reshape function:

Bnew = B.reshape((3, 3, 1)) 

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.