如何调用numpy数组中的元素?

时间:2010-08-27 08:48:54

标签: python arrays numpy

这是一个非常简单的问题,但我找不到答案。 如何调用numpy数组中的元素?

import numpy as np

arr = np.array([[1,2,3,4,5],[6,7,8,9,10]])

print arr(0,0)

上面的代码不起作用。

5 个答案:

答案 0 :(得分:36)

只需使用方括号:

print arr[1,1]

答案 1 :(得分:5)

<强> 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

但要理解为什么slicing在更多方面有用{/ p>

>>> 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]])

答案 2 :(得分:1)

此外,您可以尝试使用ndarray.item(),例如arr.item((0, 0))(行距+行距索引)或arr.item(0)(展平索引),其文档https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.item.html < / p>

答案 3 :(得分:0)

如果您使用的是numpy,并且您的数组是np.arraynp.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

(P.S。:使用numpy.array_split()时可能很有用)

答案 4 :(得分:0)

使用numpy。数组。 flatten()将2D NumPy数组转换为1D数组 打印(array_2d) array_1d = array_2d。 flatten()展平CAST(dbo.srs_enl.enl_udfb AS DECIMAL(27, 2)) * CASE WHEN CAST(dbo.srs_enl.enl_udfb AS INT) < 0 THEN 0 ELSE 1 END 打印(array_1d)