[英]Python: how to get all the first values row-wise from a 2D numpy array when using a 2D boolean mask
I have two large 2D arrays, one with values and the other ones with a mask of "valid" values.我有两个大型二维数组,一个带有值,另一个带有“有效”值的掩码。
vals = np.array([
[5, 2, 4],
[7, 8, 9],
[1, 3, 2],
])
valid = np.array([
[False, True, True],
[False, False, True],
[False, True, True],
])
My goal is to get, for each row, the first value when valid==True
, and obtain a vector of that sort: [2, 9, 3]
, in the fastest possible way.我的目标是在
valid==True
时为每一行获取第一个值,并以最快的方式获取该类型的向量: [2, 9, 3]
。
I tried applying the mask and querying from it, but it destroys the structure:我尝试应用掩码并从中查询,但它破坏了结构:
vals[valid]
> array([2, 4, 9, 3, 2])
I tried looping through all the indices, but I am wondering if there is a faster and vectorized way of doing that.我尝试遍历所有索引,但我想知道是否有更快的矢量化方法来做到这一点。 Thank you!
谢谢!
Try:尝试:
vals[np.arange(len(vals)), np.argmax(valid,axis=1)]
Or use np.take_along_axis
:或者使用
np.take_along_axis
:
np.take_along_axis(vals, np.argmax(valid,axis=1)[:,None], axis=1).ravel()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.