Gary.Di
Gary.Di

Reputation: 33

numpy 3 dimension array middle indexing bug

I seems found a bug when I'm using python 2.7 with numpy module:

import numpy as np
x=np.arange(3*4*5).reshape(3,4,5)
x

Here I got the full 'x' array as follows:

array([[[ 0,  1,  2,  3,  4],
        [ 5,  6,  7,  8,  9],
        [10, 11, 12, 13, 14],
        [15, 16, 17, 18, 19]],

       [[20, 21, 22, 23, 24],
        [25, 26, 27, 28, 29],
        [30, 31, 32, 33, 34],
        [35, 36, 37, 38, 39]],

       [[40, 41, 42, 43, 44],
        [45, 46, 47, 48, 49],
        [50, 51, 52, 53, 54],
        [55, 56, 57, 58, 59]]])

Then I try to indexing single row values in sheet [1]:

x[1][0][:]

Result:

array([20, 21, 22, 23, 24])

But something wrong while I was try to indexing single column in sheet [1]:

x[1][:][0]

Result still be the same as previous:

array([20, 21, 22, 23, 24])

Should it be array([20, 25, 30, 35])??

It seems something wrong while indexing the middle index with range?

Upvotes: 3

Views: 131

Answers (2)

Ohad Eytan
Ohad Eytan

Reputation: 8464

No, it's not a bug.

When you use [:] you are using slicing notation and it takes all the list:

l = ["a", "b", "c"]
l[:]
#output:
["a", "b", "c"]

and in your case:

x[1][:]
#output:
array([[20, 21, 22, 23, 24],
       [25, 26, 27, 28, 29],
       [30, 31, 32, 33, 34],
       [35, 36, 37, 38, 39]])

What you realy wish is using numpy indexing notation:

x[1, : ,0]
#output:
array([20, 25, 30, 35])

Upvotes: 3

szym
szym

Reputation: 5846

This is not a bug. x[1][:][0] is not a multiple index ("give me the elements where first dimension is 1, second is any, third is 0"). Instead, you are indexing three times, three objects.

x1 = x[1]     # x1 is the first 4x5 subarray
x2 = x1[:]    # x2 is same as x1
x3 = x2[0]    # x3 is the first row of x2

To use multiple index, you want to do it in a single slice:

x[1, :, 0]

Upvotes: 1

Related Questions