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!

yogz123
  • 703
  • 3
  • 8
  • 25

2 Answers2

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)
Paul Panzer
  • 51,835
  • 3
  • 54
  • 99
  • 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 Jan 30 '18 at 17:33
  • @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](https://stackoverflow.com/q/38774922/7207392). It's a similar post but the people there are more knowledgable than I am. – Paul Panzer Jan 30 '18 at 18:15
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)) 
Blackecho
  • 1,226
  • 5
  • 18
  • 26