[英]How to perform operations on certain rows of one np array based on conditions of another np array using numpy methods?
For example, I have one np array A = [[30, 60, 50...], [ 15, 20, 18...], [21, 81, 50...]...]
of size (N, 10)
.例如,我有一个 np 数组
A = [[30, 60, 50...], [ 15, 20, 18...], [21, 81, 50...]...]
大小(N, 10)
。
And I have another np array B = [1, 1, 0...]
of size (N, )
.我还有另一个大小为
(N, )
的 np 数组B = [1, 1, 0...]
。
I want to do operations Eg I want all the sums of each column in A but only for rows where B==1.我想做操作 例如,我想要 A 中每一列的所有总和,但只适用于 B==1 的行。 How would I do that without using any loops and just numpy methods?
如果不使用任何循环而仅使用 numpy 方法,我将如何做到这一点?
So if I want sum of columns in A for indices where B == 1:因此,如果我想要 A 中的列总和用于 B == 1 的索引:
result = 30 + 15 because the first two indices in B are 1 but the third index is 0 so I wouldn't include it in the sum.结果 = 30 + 15 因为 B 中的前两个索引是 1 但第三个索引是 0 所以我不会将它包含在总和中。
Use np.compress
and sum
along axis=0使用
np.compress
和沿axis = 0 sum
>>> A = [[30, 60, 50], [ 15, 20, 18], [21, 81, 50]]
>>> B = [1, 1, 0]
>>> np.compress(B, A, axis=0).sum(0)
array([45, 80, 68])
If array, use np.nonzero
on B
:如果是数组,请在
B
上使用np.nonzero
:
>>> A = np.array([[30, 60, 50], [ 15, 20, 18], [21, 81, 50]])
>>> A[np.nonzero(B)].sum(0)
array([45, 80, 68])
Another way:另一种方式:
>>> A[B.astype(bool)].sum(0)
array([45, 80, 68])
If you want 0
s:如果你想要
0
秒:
>>> np.compress(B==0, A, axis=0).sum(0)
# Or,
>>> A[np.nonzero(B==0)].sum(0)
# Or,
>>> A[~B.astype(bool)].sum(0)
If you want both 1
s and 0
s, obviously:如果你想要
1
s 和0
s,显然:
>>> A.sum(0)
You can convert B
to bool
type and mask A
.您可以将
B
转换为bool
类型并掩码A
。 Then you can get the sum
along columns.然后你可以得到沿列的
sum
。
A = np.array([[30, 60, 50], [ 15, 20, 18], [21, 81, 50]])
B = np.array([1, 1, 0])
A[B.astype(np.bool)].sum(axis=0)
array([45, 80, 68])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.