这个问题看起来很简单,但我找不到答案。如何调用Numpy数组中的元素?
import numpy as np
arr = np.array([[1,2,3,4,5],[6,7,8,9,10]])
print arr(0,0)
上述代码不起作用。
只需使用方括号即可:
print arr[0,0]
TL;DR:
使用切片操作(slicing):
>>> 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
长话短说:
希望这对您有所帮助:
>>> 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
但是要理解为什么在更多维度上切片很有用:
>>> 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]])
numpy
,并且您的数组是包含np.array
元素的np.array
,例如:
A = np.array([np.array([10,11,12,13]), np.array([15,16,17,18]), np.array([19,110,111,112])])
如果您想访问内部元素(如10,11,12 13,14.......
),则请使用:
A[0][0]
而不是A[0,0]
例如:>>> import numpy as np
>>>A = np.array([np.array([10,11,12,13]), np.array([15,16,17,18]), np.array([19,110,111,112])])
>>> A[0][0]
>>> 10
>>> A[0,0]
>>> Throws ERROR
numpy.array_split()
时可能会有用)ndarray.item()
,例如,arr.item((0, 0))
(行id+列id转换为索引)或arr.item(0)
(扁平化索引),其文档https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.item.html。array_2d
print(array_1d)
arr[0,0]
而不是arr[1,1]
。 - kennytm