根据第一次遇到更改数组中元素的值

时间:2018-01-13 22:18:06

标签: python arrays numpy

我有一组数组,如下所示:

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

我想更改此数组,以便第一次在内部数组中遇到1时,剩余的向下内部数组在此位置变为1:

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

有什么办法吗?

3 个答案:

答案 0 :(得分:2)

对我来说,这看起来像个笨拙的阵列。

选项1
您可以利用this answer来提供有效的解决方案。

>>> (x.cumsum(axis=0) > 0).astype(int)
array([[0, 0, 1, 1],
       [0, 0, 1, 1],
       [0, 0, 1, 1],
       [0, 0, 1, 1],
       [1, 0, 1, 1],
       [1, 0, 1, 1],
       [1, 0, 1, 1],
       [1, 0, 1, 1]])

x是您的输入。

选项2
np.cumsum np.maximum.accumulate -

>>> np.maximum.accumulate(x)
array([[0, 0, 1, 1],
       [0, 0, 1, 1],
       [0, 0, 1, 1],
       [0, 0, 1, 1],
       [1, 0, 1, 1],
       [1, 0, 1, 1],
       [1, 0, 1, 1],
       [1, 0, 1, 1]], dtype=int32)

如果您的数组可以包含大于1的值,请在结尾处添加clip来电。

np.maximum.accumulate(x).clip(None, 1)

答案 1 :(得分:2)

作为列表,您可以这样做:

data= [[0, 0, 1, 1],
       [0, 0, 1, 0],
       [0, 0, 1, 0],
       [0, 0, 1, 0],
       [1, 0, 1, 1],
       [1, 0, 1, 1],
       [0, 0, 0, 0],
       [1, 0, 0, 1]]

d = {}    # store the index if they get 1 the first time
for r in data:
    for idx in range(len(r)):
        if (r[idx] == 1):
            d[idx] = 1        # this ones going to be 1 all the time now

        r[idx] = r[idx] or d.get(idx,0)  # leverages 0 == False and get  with 0 default

print(data)

输出:

[[0, 0, 1, 1],
 [0, 0, 1, 1],
 [0, 0, 1, 1],
 [0, 0, 1, 1],
 [1, 0, 1, 1],
 [1, 0, 1, 1],
 [1, 0, 1, 1],
 [1, 0, 1, 1]] 

答案 2 :(得分:-2)

你可以使用矢量数组并找到数组中的第一个匹配项 要么 可以使用需要时间O(n)

的循环
for(i=0;i < n;i++)

    if(a[i]==1)
      {
        c1++;
        break;
      }

for(j=I; j < n;j++)
    a[i]=1;
相关问题