简体   繁体   English

使用Numpy计数范围内的数字

[英]Using Numpy to Count Numbers in a range

I've been trying to write some code which will add the numbers which fall into a certain range and add a corresponding number to a list. 我一直在尝试编写一些代码,这些代码将添加落入一定范围内的数字并将相应的数字添加到列表中。 I also need to pull the range from a cumsum range. 我还需要从累积范围中拉出范围。

numbers = []
i=0

z = np.random.rand(1000)
arraypmf = np.array(pmf)
summation = np.cumsum(z)

while i < 6:
   index = i-1

    a = np.extract[condition, z] # I can't figure out how to write the condition.
    length = len(a)
    length * numbers.append(i)

I'm not entirely sure what you're trying to do, but the easiest way to do conditions in numpy is to just apply them to the whole array to get a mask: 我不确定您要做什么,但是在numpy执行条件的最简单方法是将它们应用于整个数组以获得掩码:

mask = (z >= 0.3) & (z < 0.6)

Then you can use, eg, extract or ma if necessary—but in this case, I think you can just rely on the fact that True==1 and False==0 and do this: 然后,您可以根据需要使用例如extractma ,但是在这种情况下,我认为您可以依靠True==1False==0的事实来做到这一点:

zm = z * mask

After all, if all you're doing is summing things up, 0 is the same as not there, and you can just replace len with count_nonzero . 毕竟,如果您要做的只是将所有内容加总,则0等于不存在的数字,您可以将len替换为count_nonzero

For example: 例如:

In [588]: z=np.random.rand(10)
In [589]: z
Out[589]: 
array([ 0.33335522,  0.66155206,  0.60602815,  0.05755882,  0.03596728,
        0.85610536,  0.06657973,  0.43287193,  0.22596789,  0.62220608])
In [590]: mask = (z >= 0.3) & (z < 0.6)
In [591]: mask
Out[591]: array([ True, False, False, False, False, False, False,  True, False, False], dtype=bool)
In [592]: z * mask
Out[592]: 
array([ 0.33335522,  0.        ,  0.        ,  0.        ,  0.        ,
        0.        ,  0.        ,  0.43287193,  0.        ,  0.        ])
In [593]: np.count_nonzero(z * mask)
Out[593]: 2
In [594]: np.extract(mask, z)
Out[594]: array([ 0.33335522,  0.43287193])
In [595]: len(np.extract(mask, z))
Out[595]: 2

Here is another approach to do (what I think) you're trying to do: 这是您尝试做的另一种方法(我认为):

import numpy as np
z = np.random.rand(1000)
bins = np.asarray([0, .1, .15, 1.])

# This will give the number of values in each range
counts, _ = np.histogram(z, bins)

# This will give the sum of all values in each range
sums, _ = np.histogram(z, bins, weights=z)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM