通过mask提取list中的目标元素

需求

需求描述:
有2个list,一个是待处理的list,另一个是mask。现在想要根据mask提取出待处理list中的元素。

代码

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/1/31 17:38
# @Author  : JasonLiu
# @File    : test.py
import numpy as np
import pdb
# function to create masked array
def masking(ar1, ar2):
    # masking the array1 by using array2
    # where array2 mod 7 is true
    # mask = np.ma.masked_where(ar2 % 7, ar1)
    mask = np.ma.masked_where(ar2 != 1, ar1)
    return mask
# main function
if __name__ == '__main__':
    # creating two arrays
    x = np.array([1, 2, 4, 5, 7, 8, 9])
    # y = np.array([10, 12, 14, 5, 7, 0, 13])
    y = np.array([1, 1, 0, 1, 1, 0, 1])
    # calling masking function to get
    # masked array
    masked = masking(x, y)
    print("masked=", masked)
    # getting the values as 1-d array which
    # are non masked
    masked_array = np.ma.compressed(masked)
    # print("masked_array=", masked_array)
    # printing the resultant array after masking
    print(f'Masked Array is:{masked_array}')

运行结果如下:

masked= [1 2 -- 5 7 -- 9]
Masked Array is:[1 2 5 7 9]

猜你喜欢

转载自blog.csdn.net/ljp1919/article/details/130774054