在 numpy 数组中填充某个值之间的值 [英] Fill values in numpy array that are between a certain value

查看:63
本文介绍了在 numpy 数组中填充某个值之间的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个如下所示的数组:

Let's say I have an array that looks like this:

a = np.array([0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0])

我想用 1 填充 1 之间的值.所以这将是所需的输出:

I want to fill the values that are between 1's with 1's. So this would be the desired output:

a = np.array([0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0])

我查看了这个答案,结果如下:

I have taken a look into this answer, which yields the following:

array([0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
   1, 1]) 

我确信这个答案非常接近我想要的输出.但是,尽管尝试了无数次,但我无法更改此代码使其按我想要的方式工作,因为我对 numpy 数组并不那么精通.非常感谢任何帮助!

I am sure this answer is really close to the output I want. However, although tried countless times, I can't change this code into making it work the way I want, as I am not that proficient with numpy arrays. Any help is much appreciated!

推荐答案

试试这个

b = ((a == 1).cumsum() % 2) | a

Out[10]:
array([0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0], dtype=int32)

<小时>

来自@Paul Panzer:使用 ufunc.accumulatebitwise_xor

b = np.bitwise_xor.accumulate(a)|a

这篇关于在 numpy 数组中填充某个值之间的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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