See*_*eer 3 python numpy sum modulus
我正在寻找一种矢量化方法,用于求和numpy数组的所有元素,这些元素可被5整除.
例如,如果我有
test = np.array([1,5,12,15,20,22])
Run Code Online (Sandbox Code Playgroud)
我想返回40.我知道np.sum方法,但有没有办法在给定X%5 == 0条件的情况下使用向量化?
我们可以使用mask
匹配boolean-indexing
来选择那些元素,然后简单地将它们相加,就像这样 -
test[test%5==0].sum()
Run Code Online (Sandbox Code Playgroud)
逐步运行示例 -
# Input array
In [48]: test
Out[48]: array([ 1, 5, 12, 15, 20, 22])
# Mask of matches
In [49]: test%5==0
Out[49]: array([False, True, False, True, True, False], dtype=bool)
# Select matching elements off input
In [50]: test[test%5==0]
Out[50]: array([ 5, 15, 20])
# Finally sum those elements
In [51]: test[test%5==0].sum()
Out[51]: 40
Run Code Online (Sandbox Code Playgroud)