掩模numpy阵列并提取符合条件的值

发布于 2025-02-04 19:44:59 字数 540 浏览 3 评论 0原文

如何正确掩盖两个Numpy阵列?我想找到不等于255pe值。我还希望我所需的输出数组的大小与pdpe,ie,(7,7) ,并用填充0是
实现这一目标的最有效方法是什么?

import numpy as np

pd = np.random.randint(254,256, size=(7,7))
pe = np.random.randint(0,7, size=(7,7))

所需的输出

[[6 6 0 0 6 6 1]
 [2 6 1 1 5 6 3]
 [3 4 6 6 3 5 6]
 [3 5 0 3 2 0 0]
 [0 3 6 1 3 6 1]
 [6 3 4 1 0 3 1]
 [6 0 4 2 2 6 4]]

非常感谢

How can I mask two NumPy arrays properly? I want find pe values that are not equal to 255, for example. I also want my desired output array be the same size aspd and pe, i.e., (7, 7) and filled with 0's.

What is the most efficient way to achieve this?

import numpy as np

pd = np.random.randint(254,256, size=(7,7))
pe = np.random.randint(0,7, size=(7,7))

Desired output

[[6 6 0 0 6 6 1]
 [2 6 1 1 5 6 3]
 [3 4 6 6 3 5 6]
 [3 5 0 3 2 0 0]
 [0 3 6 1 3 6 1]
 [6 3 4 1 0 3 1]
 [6 0 4 2 2 6 4]]

Many thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

画离情绘悲伤 2025-02-11 19:44:59

逻辑索引似乎是所有选项中最简单的。

import numpy as np

pd = np.random.randint(254,256, size=(7,7))
pe = np.random.randint(0,7, size=(7,7))

pe[pd == 255] = 0

[[3 6 0 2 0 0 0]
 [0 3 4 5 2 0 5]
 [0 0 6 0 1 0 5]
 [0 3 0 4 0 6 0]
 [2 0 0 0 0 0 0]
 [2 0 4 0 0 0 5]
 [0 0 3 0 2 4 0]]

根据您的数据大小,您可以尝试其他选项:

pe = np.where(pd == 255, 0, pe)
# OR
pe = pe * (pd == 255)

但是我猜索引仍然很简单快捷。

Logical indexing seems the simplest of all options.

import numpy as np

pd = np.random.randint(254,256, size=(7,7))
pe = np.random.randint(0,7, size=(7,7))

pe[pd == 255] = 0

[[3 6 0 2 0 0 0]
 [0 3 4 5 2 0 5]
 [0 0 6 0 1 0 5]
 [0 3 0 4 0 6 0]
 [2 0 0 0 0 0 0]
 [2 0 4 0 0 0 5]
 [0 0 3 0 2 4 0]]

Based on your data size, you may try other options:

pe = np.where(pd == 255, 0, pe)
# OR
pe = pe * (pd == 255)

but I guess indexing is still simple and fast.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文