Pergunta

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)
Foi útil?

Solução

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:

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

Then you can use, e.g., 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:

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.

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

Outras dicas

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)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top