C'est une question très simple, mais je n'ai pas trouvé la réponse… .. Comment appeler un élément dans un tableau numpy?
import numpy as np
arr = np.array([[1,2,3,4,5],[6,7,8,9,10]])
print arr(0,0)
Le code ci-dessus ne fonctionne pas.
Utilisez simplement des crochets à la place:
print arr[1,1]
TL; DR:
Utiliser trancher :
>>> import numpy as np
>>>
>>> arr = np.array([[1,2,3,4,5],[6,7,8,9,10]])
>>>
>>> arr[0,0]
1
>>> arr[1,1]
7
>>> arr[1,0]
6
>>> arr[1,-1]
10
>>> arr[1,-2]
9
En long:
J'espère que cela vous aidera à comprendre:
>>> import numpy as np
>>> np.array([ [1,2,3], [4,5,6] ])
array([[1, 2, 3],
[4, 5, 6]])
>>> x = np.array([ [1,2,3], [4,5,6] ])
>>> x[1][2] # 2nd row, 3rd column
6
>>> x[1,2] # Similarly
6
Mais comprendre pourquoi trancher est utile, dans plusieurs dimensions:
>>> np.array([ [[1,2,3], [4,5,6]], [[7,8,9],[10,11,12]] ])
array([[[ 1, 2, 3],
[ 4, 5, 6]],
[[ 7, 8, 9],
[10, 11, 12]]])
>>> x = np.array([ [[1,2,3], [4,5,6]], [[7,8,9],[10,11,12]] ])
>>> x[1][0][2] # 2nd matrix, 1st row, 3rd column
9
>>> x[1,0,2] # Similarly
9
>>> x[1][0:2][2] # 2nd matrix, 1st row, 3rd column
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: index 2 is out of bounds for axis 0 with size 2
>>> x[1, 0:2, 2] # 2nd matrix, 1st and 2nd row, 3rd column
array([ 9, 12])
>>> x[1, 0:2, 1:3] # 2nd matrix, 1st and 2nd row, 2nd and 3rd column
array([[ 8, 9],
[11, 12]])
Vous pouvez également essayer d'utiliser ndarray.item()
, par exemple, arr.item((0, 0))
(rowid + colid to index) ou arr.item(0)
(aplatir l'index), sa doc https://docs.scipy.org/doc/numpy/reference/generated/numpy .ndarray.item.html