Why doing array[array%10] on a 2-D numpy array returns a 3-D array?

Viewed 28

So I have a 2-D array made using

array = numpy.arange(1, 101).reshape(10,10)

and when I do something like array[array>0] I get a 1-D array, but when I do array[array%10] I get a 3-D array. I don't know what is happening here.

1 Answers

I'm wondering what you were expecting that to do. In a command line, you should type array > 0 and see what you get. That's an array of booleans. When you do indexing with an array of booleans, that selects certain elements from the array, on a matching basis. In that case, every element was true, so you get all 100 elements.

But array%10 returns a 2D array of numbers. Numpy interprets those as the indices of the rows you want. The first row of array%10 is [1,2,3,4,5,6,7,8,9,0]. So, numpy builds you a plane containing those rows of the array. The second row happens to be the same, so you end up with ten identical 10x10 planes selected from the original array.

Related