如何计算Numpy数组中某个范围内的值? [英] How to count values in a certain range in a Numpy array?
问题描述
我有一个 NumPy 值数组.我想计算这些值中有多少在特定范围内,比如 x<100 和 x>25.我已经阅读了有关计数器的信息,但它似乎只对特定值有效,而不是对值范围有效.我已经搜索过,但没有找到任何关于我的具体问题的信息.如果有人能指出我正确的文档,我将不胜感激.谢谢
I have a NumPy array of values. I want to count how many of these values are in a specific range say x<100 and x>25. I have read about the counter, but it seems to only be valid for specif values not ranges of values. I have searched, but have not found anything regarding my specific problem. If someone could point me towards the proper documentation I would appreciate it. Thank you
我已经试过了
X = array(X)
for X in range(25, 100):
print(X)
但它只给了我 25 到 99 之间的数字.
But it just gives me the numbers in between 25 and 99.
编辑我使用的数据是由另一个程序创建的.然后我使用脚本读取数据并将其存储为列表.然后我把这个列表用 array(r) 转换成一个数组.
EDIT The data I am using was created by another program. I then used a script to read the data and store it as a list. I then took the list and turned it in to an array using array(r).
编辑
运行结果
>>> a[0:10]
array(['29.63827346', '40.61488812', '25.48300065', '26.22910525',
'42.41172923', '20.15013315', '34.95323355', '13.03604098',
'29.71097606', '9.53222141'],
dtype='<U11')
推荐答案
如果你的数组被称为a
,则满足25的元素数<×<100
是
If your array is called a
, the number of elements fulfilling 25 < x < 100
is
((25 < a) & (a < 100)).sum()
表达式 (25 < a) &(a < 100)
产生一个与 a
形状相同的布尔数组,所有满足条件的元素的值为 True
.对这个布尔数组求和会将 True
值视为 1
并将 False
值视为 0
.
The expression (25 < a) & (a < 100)
results in a Boolean array with the same shape as a
with the value True
for all elements that satisfy the condition. Summing over this Boolean array treats True
values as 1
and False
values as 0
.
这篇关于如何计算Numpy数组中某个范围内的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!