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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

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.