仅通过第一个位置创建蒙版 [英] Create mask by first positions only

查看:137
本文介绍了仅通过第一个位置创建蒙版的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有数组:

a = np.array([[ 0,  1,  2,  0,  0,  0],
              [ 0,  4,  1, 35,  0, 10],
              [ 0,  0,  5,  4,  0,  4],
              [ 1,  2,  5,  4,  0,  4]])

我只需要从第一个连续选择 0每行

I need select only from first consecutive 0 in each row:

[[  True   False  False  False  False  False]
 [  True   False  False  False  False  False]
 [  True   True   False  False  False  False]
 [  False  False  False  False  False  False]]

我试试:

a[np.arange(len(a)), a.argmax(1): np.arange(len(a)), [0,0,0]] = True

但这是错误的。

推荐答案

你可以使用 np.cumsum

假设:您只在每行的开头寻找零。

Assumption: you are looking for zeros only at the start of each row.

a = np.array([[ 0,  1,  2,  0,  0,  0],
              [ 0,  4,  1, 35,  0, 10],
              [ 0,  0,  5,  4,  0,  4]])

a.cumsum(axis=1) == 0
array([[ True, False, False, False, False, False],
       [ True, False, False, False, False, False],
       [ True,  True, False, False, False, False]], dtype=bool)

基数:持有,只要每行的累积和为0。

Basis: holds True for as long as the cumulative sum is 0 along each row.

容易出错:带负数的数组会导致这个失败。即对于 [ - 1,1] ,这将在第1位评估为 True

Error-prone: an array with negative ints would cause this to fail. I.e. for [-1, 1], this would evaluate to True at position 1.

这篇关于仅通过第一个位置创建蒙版的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆