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

0 投票
3 回答
3207 浏览
提问于 2025-04-18 14:26

我想要把数组 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 个回答

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

另外

3

我会使用带掩码的数组,然后沿着某个方向进行求和:

out = np.ma.masked_greater_equal(np.random.random((surveys,voters)), 0.49)
rep = out.sum(axis=1)
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

撰写回答