Numpy Array Indexing Behavior

I played with numpy array indexing and found this weird behavior. When I index np.arrayor list, it works as expected:

 In[1]: arr = np.arange(10).reshape(5,2)
        arr[ [1, 1] ]
Out[1]: array([[2, 3],
               [2, 3]])

But when I put it tuple, it gives me one element:

 In[1]: arr = np.arange(10).reshape(5,2)
        arr[ (1, 1) ]
Out[1]: 3

There is also some weird behavior tuplevs listwith arr.flat:

 In[1]: arr = np.arange(10).reshape(5,2)

 In[2]: arr.flat[ [3, 4] ]
Out[2]: array([3, 4])

 In[3]: arr.flat[ (3, 4) ]
Out[3]: IndexError: unsupported iterator index

I can not understand what is happening under the hood? What is the difference between tupleand listin this case?

Python 3.5.2
NumPy 1.11.1

+4
source share
2 answers

, , , . /. , - :

import numpy as np
arr = np.arange(10).reshape(5,2)
arr[2,1] == arr[(2,1)] # exact same thing: 2,1 matrix element

( ) -:

arr[[2,1]]

arr 1, 2, arr[2]==arr[2,:], arr[1]==arr[1,:] ( 2 1) .

:

print(arr[1:3,0:2])
print(arr[[1,2],[0,1]])

- , 1 2 0 1 ; 2- . - , arr[1,0],arr[2,1] , .. , , , zip() .

flat : flatiter . help(arr.flat):

class flatiter(builtins.object)
 |  Flat iterator object to iterate over arrays.
 |  
 |  A `flatiter` iterator is returned by ``x.flat`` for any array `x`.
 |  It allows iterating over the array as if it were a 1-D array,
 |  either in a for-loop or by calling its `next` method.

, arr.flat 1d-.

arr.flat[ [3, 4] ]

1d, ; .

arr.flat[ (3,4) ]

(3,4) 1d (!), . , IndexError, , , arr.flat .

+2
In [387]: arr=np.arange(10).reshape(5,2)

2 arr

In [388]: arr[[1,1]]
Out[388]: 
array([[2, 3],
       [2, 3]])

, ( : ...)

In [389]: arr[[1,1],:]
Out[389]: 
array([[2, 3],
       [2, 3]])

: arr[np.array([1,1]),:]. ( .)

tuple , . , 1, 1.

In [390]: arr[(1,1)]
Out[390]: 3
In [391]: arr[1,1]
Out[391]: 3

arr[1,1] arr.__getitem__((1,1)). Python 1,1 (1,1).

arr.flat , 1d. np.arange(10)[[2,3]] 2 , np.arange(10)[(2,3)] - 2d, .

. . , , .

numpy

numpy: ?

+1

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


All Articles