【问题标题】:Check every 4 values and change values accordingly in an np array检查每 4 个值并在 np 数组中相应地更改值
【发布时间】:2022-12-18 22:11:42
【问题描述】:

您好,我有一个包含 0 和 1 的 np 数组。我想检查每 4 个值,如果至少有一个 (1) 将所有四个值都等于 (1)。否则将它们全部归零。

你知道怎么做吗?谢谢 这是一个样本

np= [ 0 0 0 0 1 1 1 1 0 0 1 0 0 0 0 0 ]

np_corrected=np= [ 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 ]

非常感谢,希望问题现在清楚了!

【问题讨论】:

    标签: numpy


    【解决方案1】:

    可能不是最短的解决方案,但绝对有效且快速:

    1. 重塑
    2. 创建一个面具
    3. 应用掩码并获得结果:
      import numpy as np
      array = np.array([0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0])
      array
      groups = array.reshape(-1, 4)  # group every 4 elements into new columns
      groups
      mask = groups.sum(axis=1)>0  # identify groups with at least one '1'
      mask
      np.logical_or(groups.T, mask).T.astype(int).flatten()
      # swap rows and columns in groups, apply mask, swap back, 
      # replace True/False with 1/0 and restore original shape
      

      返回(在 Jupyter 笔记本中):

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-01
    • 2019-03-01
    • 2010-10-26
    • 1970-01-01
    • 2017-03-15
    • 2011-07-24
    • 2020-08-11
    • 2019-04-23
    相关资源
    最近更新 更多