Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dealing with multi-dimensional arrays when ndims not known in advance

I am working with data from netcdf files, with multi-dimensional variables, read into numpy arrays. I need to scan all values in all dimensions (axes in numpy) and alter some values. But, I don't know in advance the dimension of any given variable. At runtime I can, of course, get the ndims and shapes of the numpy array. How can I program a loop thru all values without knowing the number of dimensions, or shapes in advance? If I knew a variable was exactly 2 dimensions, I would do

shp=myarray.shape
for i in range(shp[0]):
  for j in range(shp[1]):
    do_something(myarray[i][j])
like image 815
Micha Avatar asked Mar 21 '23 20:03

Micha


1 Answers

You should look into ravel, nditer and ndindex.

# For the simple case
for value in np.nditer(a):
    do_something_with(value)

# This is similar to above
for value in a.ravel():
    do_something_with(value)

# Or if you need the index
for idx in np.ndindex(a.shape):
    a[idx] = do_something_with(a[idx])

On an unrelated note, numpy arrays are indexed a[i, j] instead of a[i][j]. In python a[i, j] is equivalent to indexing with a tuple, ie a[(i, j)].

like image 189
Bi Rico Avatar answered Apr 16 '23 20:04

Bi Rico