James
James

Reputation: 2795

numpy array slicing unxpected results

I don't understand the behavior below. numpy arrays can generally be accessed through indexing, so [:,1] should be equivalent to [:][1], or so I thought. Could someone explain why this is not the case?

>>> a = np.array([[1, 2, 3], [4, 5, 6]])  
>>> a[:,1]  
array([2, 5])  
>>> a[:][1]  
array([4, 5, 6])

Thanks!

Upvotes: 1

Views: 103

Answers (3)

BrenBarn
BrenBarn

Reputation: 251355

Those two forms of indexing are not the same. You should use [i, j] and not [i][j]. Even where both work, the first will be faster (see this question).

Using two indices [i][j] is two operations. It does the first index and then does the second on the result of the first operation. [:] just returns the entire array, so your first one is equivalent to array[1]. Since only one index is passed, it assumed to refer to the first dimension (rows), so this means "get row 1". Using one compound index [i, j] is a single operation that uses both indexing conditions at once, so array[:, 1] returns "all rows, column 1".

Upvotes: 5

kiriloff
kiriloff

Reputation: 26333

>>> a = np.array([[1, 2, 3], [4, 5, 6]])
>>> a[:,1]
array([2, 5])

you select the second dimension (column of your matrix) and take the element 1 in this dimension. the same way, a[:,0] selects the first column, here array([1,4]), a[:,2] the third column.

As was previously said, a[:] copies your list (be a numpy array or a list).

Upvotes: 0

Joran Beasley
Joran Beasley

Reputation: 113940

[:] creates a copy of your list ...

so that is essentially the same as

array[1] == array[:][1]

which correctly returns in this case [4,5,6]

while array[:,1] says return the first column which is indeed [2,5]

eg

a = [
      [1,2,3],
      [4,5,6]
    ]

so as you can see column 0 (a[:,0] )would be [1,4] and column 2(a[:,2]) would be [3,6]

meanwhilea[1] refers to the row 1 (or [4,5,6]) and a[0] would be the 0 row (or [1,2,3])

Upvotes: 1

Related Questions