Francisco Andrés
Francisco Andrés

Reputation: 111

Slicing using arrays/indices

I am trying to iteratively access an numpy array using indices and arrays. The following example pretty much sums up my problem:

x = np.arange(12)
x.shape = (3,2,2)
nspace = np.array([[0,0], [0,1], [1,0], [1,1]])
for it in range(len(nspace)):
    x[:,nspace(it)] = np.array([1,1,1])

If things worked the way I am thinking, the code would print 4 separate arrays:

[0,4,8]
[1,5,9]
[2,6,10]
[3,7,11]

But I get an error. I understand the my indexing is wrong, but I cannot figure out how to get the result I want.

It is important that everything happens within a loop because I want to be able to change the dimensions of x.

EDIT0: I need a general solution that does require. me to write: space[0,0], space[0,1], etc.

EDIT1: I changed the print to an assignment operation because what actually need is to assign the result of a function that I call inside the loop.

EDIT2: I did not include the Traceback because I doubt it will be useful. Anyway, here it is:

Traceback (most recent call last):

  File "<ipython-input-600-50905b8b5c4d>", line 5, in <module>
    print(x[:,nspace(it)])

TypeError: 'numpy.ndarray' object is not callable

Upvotes: 0

Views: 80

Answers (3)

roganjosh
roganjosh

Reputation: 13185

You don't need to use the for loop. Use reshape and transpose.

x.reshape(3, 4).T

Gives:

array([[ 0,  4,  8],
       [ 1,  5,  9],
       [ 2,  6, 10],
       [ 3,  7, 11]])

If you wanted to iterate the result:

for row in x.reshape(3, 4).T:
    print(row)

Upvotes: 1

onodip
onodip

Reputation: 655

You get the error, because you should have square brackets for element access on the last line.

import numpy as np

x = np.arange(12)
x.shape = (3,2,2)
nspace = np.array([[0,0], [0,1], [1,0], [1,1]])
for it in range(len(nspace)):
    print(x[:,nspace[it]])

EDIT:

And one possible solution to get your expected result:

import numpy as np

x = np.arange(12)
x.shape = (3,2,2)
nspace = np.array([[0,0], [0,1], [1,0], [1,1]])

y = x.flatten()

for i in range(x.size//x.shape[0]):
    print y[i::4]

Upvotes: 0

Sheldore
Sheldore

Reputation: 39072

You need to provide the first and the second index and use [] brackets instead of () to access the array elements.

import numpy as np

x = np.arange(12)
x.shape = (3,2,2)

for it in range(len(nspace)):
    print(x[:,nspace[it][0], nspace[it][1]])

Output

[0 4 8]
[1 5 9]
[ 2  6 10]
[ 3  7 11]

You can also use reshape directly as

x = np.arange(12).reshape(3,2,2)

Upvotes: 0

Related Questions