pauld
pauld

Reputation: 421

How do I sum only certain elements from an array?

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!

Upvotes: 0

Views: 3294

Answers (3)

toine
toine

Reputation: 2026

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

Upvotes: 0

deinonychusaur
deinonychusaur

Reputation: 7304

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)

Upvotes: 3

Cory Kramer
Cory Kramer

Reputation: 118001

>>> 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

Upvotes: 2

Related Questions