Indexing A Numpy array with list and tuple gives different results?

Code example:

import numpy as np
a = np.zeros((5,5))
a[[0,1]] = 1     #(list of indices)
print('results with list based indexing\n', a)

a = np.zeros((5,5))
a[(0,1)] = 1   #(tuple of indices)
print('results with tuple based indexing\n',a)

Result:

results with list based indexing
 [[ 1.  1.  1.  1.  1.]
  [ 1.  1.  1.  1.  1.]
  [ 0.  0.  0.  0.  0.]
  [ 0.  0.  0.  0.  0.]
  [ 0.  0.  0.  0.  0.]]

results with tuple based indexing
[[  0.   1.   0.   0.   0.]
 [  0.   0.   0.   0.   0.]
 [  0.   0.   0.   0.   0.]
 [  0.   0.   0.   0.   0.]
 [  0.   0.   0.   0.   0.]]

As you must have noticed, an index array with a list gave a different result than with a set of identical indices. I am using python3 with numpy version 1.13.3

What is the fundamental difference between indexing a numpy array with a list and tuple?

+4
source share
2 answers

By design. The numerical syntax of getitem and setitem is not ducky, because different types are used to support various functions . This is just old __setitem__:

a[(0,1)] = 1

This is the same as for a[0,1] = 1. In both cases, the ndarray setitem receives two arguments: a tuple for the index (0, 1)and a value 1.

a[[0,1]] = 1

broadcasting. a[0:2] = 1, / , a[[0,1,3]]. 1 "" 0 1 .

+4

.

a[[0],[1]] = 1
a[(0),(1)] = 1
a[(0,),(1,)] = 1

a[0,1] = 1. , Numpy N N .

, a[[ 0,1 ]] a[ [0,1], :].

[0,1] , , :, a[[0,1],:].

wim .

!

0

Source: https://habr.com/ru/post/1694139/


All Articles