3

Say I create an array of arbitrary dimension (n).

#assign the dimension

>>> n=22

#create the numpy array

>>> TheArray=zeros([2]*n)

>>> shape(TheArray)

(2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2)

Have some code (skipped in this example) to populate the values of the array.

Now, try to access some values of the array

>>> TheArray[0:2,0:2,0:2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

array([[[ 0.,  0.],
        [ 0.,  0.]],

       [[ 0.,  0.],
        [ 0.,  0.]]])

How to make the 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 part of the syntax generalized to n?

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
user1748155
  • 1,345
  • 1
  • 9
  • 17

1 Answers1

2

One way would be to use numpy.s_:

In [55]: m = arange(2**6).reshape([2]*6)

In [56]: m.shape
Out[56]: (2, 2, 2, 2, 2, 2)

In [57]: m[:2,:2,:2,0,0,0]
Out[57]: 
array([[[ 0,  8],
        [16, 24]],

       [[32, 40],
        [48, 56]]])

In [58]: m[s_[:2, :2, :2] + (0,)*(n-3)]
Out[58]: 
array([[[ 0,  8],
        [16, 24]],

       [[32, 40],
        [48, 56]]])

And I guess you could get rid of the hardcoded -3..

In [69]: m[(s_[:2, :2, :2] + (0,)*m.ndim)[:m.ndim]]
Out[69]: 
array([[[ 0,  8],
        [16, 24]],

       [[32, 40],
        [48, 56]]])

but to be honest, I'd probably just wrap this up in a function if I needed it.

DSM
  • 342,061
  • 65
  • 592
  • 494
  • thanks. the python and numpy documentation was not clear enough to lead me to this conclusion, but after your example was provided, I was able to piece together the python and numpy documentation to understand this. – user1748155 Feb 16 '13 at 04:17