0

I want to sum only the elements from the array out that have a value less than 0.49, but I'm not sure how to implement a filter for that criteria. Here is what I have so far:

def outcome(surveys,voters):
    out = np.random.random((surveys,voters))
    rep = [0]*surveys
    for i in range(0,surveys):
        rep[i] = sum(out[i,:])
    return rep

Any help is greatly appreciated, Thanks in advance!

2
  • What is the array in your code? Commented Jul 23, 2014 at 13:41
  • numpy.random.random((x,y)) returns an x by y array of random numbers from 0 to 1. Commented Jul 23, 2014 at 13:48

3 Answers 3

3

I would use masked arrays and then just sum along the axis:

out = np.ma.masked_greater_equal(np.random.random((surveys,voters)), 0.49)
rep = out.sum(axis=1)
Sign up to request clarification or add additional context in comments.

Comments

2
>>> l = [0.25, 0.1, 0.5, 0.75, 0.1, 0.9]
>>> sum(i for i in l if i < 0.49)
0.44999999999999996

Alternatively

>>> l = [0.25, 0.1, 0.5, 0.75, 0.1, 0.9]
>>> sum(filter(lambda x: x < 0.49, l))
0.44999999999999996

Comments

0

you can use comparison directly on the array, that will return a boolean or mask array useful to access the interesting part of the array, see http://docs.scipy.org/doc/numpy/user/basics.indexing.html.

in other words,

def outcome(surveys,voters):
    out = np.random.random((surveys,voters))
    rep = [0]*surveys
    for i in range(0,surveys):
        rep[i] = sum(out[i,out[i,:]<0.49])
    return rep

1 Comment

This will sum only those larger than 0.49 rather than only those less. And while it works in principle, iterating out in python is unneccesary and by far slower than using the built in functionality of numpy

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.