改变Numpy数组中两个specfic值之间的数值。

问题描述 投票:2回答:1

在一个二进制的numpy数组中,我想选择1,并将所有0之间的数字转换为1。

例如

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

应该被转换为:

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

或者如果我有下面的数组,他们应该保持不变。

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

它们应该保持不变。有什么快速实现的方法吗?

python python-3.x numpy numpy-ndarray
1个回答
4
投票

我的方法是

start, end = a.argmax(), a[::-1].argmax() + 1

# only update if there is at least a one:
if a[start]==1:
    a[start:-end] = 1
© www.soinside.com 2019 - 2024. All rights reserved.