ndarray.item(arg)和ndarry [arg]有什么区别?

col*_*ang 2 python numpy

我看了文档,但仍然不太理解doc的区别和用例item

但是最近我发现只有这种方法item可行:

a = np.array(100) # a has shape ()!
a.item() # or a.item(0)
Run Code Online (Sandbox Code Playgroud)

这是从中获取价值的唯一方法aa[0]不起作用。

Ffi*_*ydd 5

ndarray.item允许您使用平面索引而不是使用[]符号来解释数组。这使您可以执行以下操作:

import numpy as np

a = np.arange(16).reshape((4,4))

print(a)
#[[ 0  1  2  3]
# [ 4  5  6  7]
# [ 8  9 10 11]
# [12 13 14 15]]

print(a[2,2]) # "Normal" indexing, taking the 3rd element from the 3rd row
# 10

print(a.item(12)) # Take the 12th element from the array, equal to [3,0]
# 12
Run Code Online (Sandbox Code Playgroud)

它还使您可以轻松地传递索引元组,如下所示:

print(a.item((1,1))) # Equivalent to a[1,1]
# 5
Run Code Online (Sandbox Code Playgroud)

最后,正如您在问题中提到的,这是一种size = 1使用Python标量获取数组元素的方法。请注意,这是不同的numpy标量,这样,如果a = np.array([1.0], dtype=np.float32)type(a[0]) != type(a.item(0))

b = np.array(3.14159)

print(b, type(b))
# 3.14159 <class 'numpy.ndarray'>

print(b.item(), type(b.item()))
# 3.14159 <class 'float'>
Run Code Online (Sandbox Code Playgroud)