需求
需求描述:
有2个list,一个是待识别抽取的目标list,另一个是mask list。现在想要根据mask list中的值提取出目标list中对应位置的元素。这种使用场景,类似做了padding后,想要通过mask重建出哪些原始是原始的数据,而非padding的数据。
比如目标list=[1, 2, 4, 5, 7, 8, 9]
,mask list=[1, 1, 0, 1, 1, 0, 1]
,那么如何抽取目标list中的元素呢?具体代码如下。
代码
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2023/6/22 10: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]