Python中List与NumPy数组查询指定数值个数及定位索引的方法
本文介绍在Python中如何统计List和NumPy数组内特定数值的出现次数及定位其索引。List可通过count()获取个数、index()获取首个位置;NumPy则利用np.sum()结合布尔判断统计个数,使用np.where()获取所有匹配元素的索引坐标,适用于数据清洗与算法开发场景。
1. List
统计元素出现次数:
使用List内置的count(obj)方法,该方法会返回目标对象obj在列表中的总出现次数。
示例代码:
list_a = [2 for x in range(5)] print(list_a) a_count = list_a.count(2) print(a_count)
运行结果:
[2, 2, 2, 2, 2]
定位元素位置:
使用List内置的index(obj)方法,该方法返回目标对象obj在列表中首次匹配到的索引位置。
示例代码:
#!/usr/bin/python aList = [123, 'xyz', 'zara', 'abc']; print "Index for xyz : ", aList.index( 'xyz' ) ; print "Index for zara : ", aList.index( 'zara' ) ;
运行结果:
Index for xyz : 1 Index for zara : 2
2. NumPy
统计元素出现次数:
利用NumPy的sum函数配合布尔表达式:np.sum( ndarray == 1 ),通过布尔数组求和得到匹配元素的总数。
示例代码:
import numpy as np a = np.ones((4, 5)) print(a) print(np.sum(a == 1))
运行结果:
[[ 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1.]] 20
定位元素位置:
利用NumPy的where函数:np.where( ndarray == obj ),返回所有匹配目标对象obj的元素索引坐标。
示例代码:
a = np.ones((4, 5)) a[1:3,1:3] = 4 print(a) print(np.sum(a == 1)) print(np.where(a == 4))
运行结果:
[[ 1. 1. 1. 1. 1.] [ 1. 4. 4. 1. 1.] [ 1. 4. 4. 1. 1.] [ 1. 1. 1. 1. 1.]] 16 (array([1, 1, 2, 2]), array([1, 2, 1, 2]))
以上介绍了Python中List与NumPy数组查询指定数值个数及定位索引的方法,供开发者参考。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









