gpt4 book ai didi

python - 如何使用 2D 蒙版过滤 3D 阵列

转载 作者:行者123 更新时间:2023-12-05 04:19:15 25 4
gpt4 key购买 nike

我有一个 (m,n,3) 数组 data,我想用 (m,n) 过滤它的值用于接收 (x,3) output 数组的掩码。

下面的代码可以工作,但我怎样才能用更有效的替代方法替换 for 循环?

import numpy as np

data = np.array([
[[11, 12, 13], [14, 15, 16], [17, 18, 19]],
[[21, 22, 13], [24, 25, 26], [27, 28, 29]],
[[31, 32, 33], [34, 35, 36], [37, 38, 39]],
])
mask = np.array([
[False, False, True],
[False, True, False],
[True, True, False],
])

output = []
for i in range(len(mask)):
for j in range(len(mask[i])):
if mask[i][j] == True:
output.append(data[i][j])
output = np.array(output)

预期的输出是

np.array([[17, 18, 19], [24, 25, 26], [31, 32, 33], [34, 35, 36]])

最佳答案

import numpy as np

data = np.array([
[[11, 12, 13], [14, 15, 16], [17, 18, 19]],
[[21, 22, 13], [24, 25, 26], [27, 28, 29]],
[[31, 32, 33], [34, 35, 36], [37, 38, 39]],
])
mask = np.array([
[False, False, True],
[False, True, False],
[True, True, False],
])

output = data[mask]

关于python - 如何使用 2D 蒙版过滤 3D 阵列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74878253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com