短小精悍算例:Python如何提取数组Numpy array中指定元素的位置索引

数组a的表达式如下:

import numpy as np
a = np.array([1, 2, 3, 2, 2, 3, 0, 8, 3])
print(a)
输出结果:[1 2 3 2 2 3 0 8 3]

现在要找出a中元素3的位置索引。

r1 = np.where(a==3)
print(type(r1))
print(r1)
输出结果:
<class 'tuple'>
(array([2, 5, 8], dtype=int64),)

可见得到的是一个tuple。如果要想得到array,采用如下表示:

r1 = np.where(a==3)
print(type(r1[0]))
print(r1[0])
输出结果:
<class 'numpy.ndarray'>
[2 5 8]

还可以使用argwhere()函数进行操作:

r2 = np.argwhere(a==3)
print(type(r2))
print(r2)
print(r2.shape)
输出结果:
<class 'numpy.ndarray'>
[[2]
 [5]
 [8]]
(3, 1)

猜你喜欢

转载自blog.csdn.net/weixin_39464400/article/details/106067112