如何仅对数组中的某些元素求和?

时间:2014-07-23 13:39:30

标签: python numpy

我想只计算数组out中值小于0.49的元素,但我不确定如何为该条件实现过滤器。以下是我到目前为止的情况:

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

非常感谢任何帮助, 提前谢谢!

3 个答案:

答案 0 :(得分:3)

我会使用蒙面数组,然后沿着轴求和:

out = np.ma.masked_greater_equal(np.random.random((surveys,voters)), 0.49)
rep = out.sum(axis=1)

答案 1 :(得分: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

可选地

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

答案 2 :(得分:0)

你可以直接在数组上使用comparison,它将返回一个布尔值或掩码数组,用于访问数组中有趣的部分,参见http://docs.scipy.org/doc/numpy/user/basics.indexing.html

换句话说,

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