繁体   English   中英

如何通过索引条件正确屏蔽 numpy 二维数组?

[英]How to mask the numpy 2D array properly by the index condition?

我有一个二维 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 工具创建这样的掩码?

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM