Simple question: In numpy how do you make a multidimensional array of arrays?

Question:

Right, perhaps I should be using the normal Python lists for this, but here goes:

I want a 9 by 4 multidimensional array/matrix (whatever really) that I want to store arrays in. These arrays will be 1-dimensional and of length 4096.

So, I want to be able to go something like

column = 0                                    #column to insert into
row = 7                                       #row to insert into
storageMatrix[column,row][0] = NEW_VALUE
storageMatrix[column,row][4092] = NEW_VALUE_2
etc..

I appreciate I could be doing something a bit silly/unnecessary here, but it will make it ALOT easier for me to have it structured like this in my code (as there’s alot of these, and alot of analysis to be done later).

Thanks!

Asked By: Duncan Tait

||

Answers:

The Tentative NumPy Tutorial says you can declare a 2D array using the comma operator:

x = ones( (3,4) )

and index into a 2D array like this:

>>> x[1,2] = 20
>>> x[1,:]                             # x's second row
array([ 1,  1, 20,  1])
>>> x[0] = a                           # change first row of x
>>> x
array([[10, 20, -7, -3],
       [ 1,  1, 20,  1],
       [ 1,  1,  1,  1]])
Answered By: David

Note that to leverage the full power of numpy, you’d be much better off with a 3-dimensional numpy array. Breaking apart the 3-d array into a 2-d array with 1-d values
may complicate your code and force you to use loops instead of built-in numpy functions.

It may be worth investing the time to refactor your code to use the superior 3-d numpy arrays.

However, if that’s not an option, then:

import numpy as np
storageMatrix=np.empty((4,9),dtype='object')

By setting the dtype to 'object', we are telling numpy to allow each element of storageMatrix to be an arbitrary Python object.

Now you must initialize each element of the numpy array to be an 1-d numpy array:

storageMatrix[column,row]=np.arange(4096)

And then you can access the array elements like this:

storageMatrix[column,row][0] = 1
storageMatrix[column,row][4092] = 2
Answered By: unutbu