python - Numpy Summation for Index in Boolean Array -


in numpy have boolean array of equal length of matrix. want run calculation on matrix elements correspond boolean array. how do this?

a: [true, false, true] b: [[1,1,1],[2,2,2],[3,3,3]] 

say function sum elements of sub arrays

index 0 true: add 3 summation (starts @ zero)

index 1 false: summation remains @ 3

index 2 true: add 9 summation total of 12

how do (the boolean , summation part; don't need how add each individual sub array)?

you can use boolean array a index rows of b, take sum of resulting (2, 3) array:

import numpy np  = np.array([true, false, true]) b = np.array([[1,1,1],[2,2,2],[3,3,3]])  # index rows of b true (i.e. first , third row of b) print(b[a]) # [[1 1 1] #  [3 3 3]]  # take sum on elements in these rows print(b[a].sum()) # 12 

it sounds benefit reading the numpy documentation on array indexing.


Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

[C++][SFML 2.2] Strange Performance Issues - Moving Mouse Lowers CPU Usage -

ios - Possible to get UIButton sizeThatFits to work? -