【问题标题】:How to mask the numpy 2D array properly by the index condition?如何通过索引条件正确屏蔽 numpy 二维数组?
【发布时间】:2021-12-30 15:39:16
【问题描述】:

我有一个 2D numpy 数组。

x = np.arange(25).reshape(5, 5)

我需要按索引条件创建掩码。例如具有偶数索引的元素。

mask = np.zeros((5, 5), dtype=bool)

for i in range(5):
    for j in range(5):
        if i % 2 == 0 and j % 2 == 0:
            mask[i][j] = True

有没有办法使用 numpy 工具创建这样的掩码?

【问题讨论】:

    标签: python arrays numpy


    【解决方案1】:

    用这个替换你的嵌套循环:

    mask[::2,::2] = True 
    

    ::2 表示每个轴上的“从头到尾,每隔一个元素”。

    【讨论】:

    • 感谢您的帮助。
    • @not_alex:不客气,欢迎来到 Stack Overflow。如果此答案解决了您的问题,您可以通过单击左侧的复选标记“接受”它。
    猜你喜欢
    • 2016-11-06
    • 1970-01-01
    • 2016-08-05
    • 1970-01-01
    • 1970-01-01
    • 2021-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多