过滤N-D numpy数组并仅保留特定元素 [英] filter a N-D numpy array and keep only specific elements

查看:77
本文介绍了过滤N-D numpy数组并仅保留特定元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个较大的N-D numpy数组.我只想将那些元素保留在另一个numpy数组中,并将其余值设置为0.

I'm dealing with a large N-D numpy array. I would like to keep only those elements present in a different numpy array, and set the remaining values to 0.

例如,如果我们考虑这个numpy数组

for example, if we consider this numpy array

array([[[36,  1, 72],
        [76, 50, 23],
        [28, 68, 17],
        [84, 75, 69]],

       [[ 5, 15, 93],
        [92, 92, 88],
        [11, 54, 21],
        [87, 76, 81]]])

,我想在所有地方都设置 0 ,但值分别为 50 11 72

and I want to set 0 in all places except where the values are 50, 11, 72

推荐答案

我通过将 reduce np.logical_or 组合起来并设置掩码,然后遍历应该保持:

I set up a mask by combining reduce with np.logical_or and iterated over the values that should remain:

import functools
import numpy as np

arr = np.array([[[36,  1, 72],
        [76, 50, 23],
        [28, 68, 17],
        [84, 75, 69]],
       [[ 5, 15, 93],
        [92, 92, 88],
        [11, 54, 21],
        [87, 76, 81]]])

# Set the values that should not
# be set to zero
vals = [11, 50, 72]

# Create a mask by looping over the above values
mask = functools.reduce(np.logical_or, (arr==val for val in vals))

masked = np.where(mask, arr, 0.)

print(masked)
> array([[[ 0.,  0., 72.],
        [ 0., 50.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.]],

       [[ 0.,  0.,  0.],
        [ 0.,  0.,  0.],
        [11.,  0.,  0.],
        [ 0.,  0.,  0.]]])

这篇关于过滤N-D numpy数组并仅保留特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆