[英]How to efficiently filter/create mask of numpy.array based on list of tuples
I try to create mask of numpy.array based on list of tuples.我尝试根据元组列表创建 numpy.array 的掩码。 Here is my solution that produces expected result:这是我产生预期结果的解决方案:
import numpy as np
filter_vals = [(1, 1, 0), (0, 0, 1), (0, 1, 0)]
data = np.array([
[[0, 0, 0], [1, 1, 0], [1, 1, 1]],
[[1, 0, 0], [0, 1, 0], [0, 0, 1]],
[[1, 1, 0], [0, 1, 1], [1, 0, 1]],
])
mask = np.array([], dtype=bool)
for f_val in filter_vals:
if mask.size == 0:
mask = (data == f_val).all(-1)
else:
mask = mask | (data == f_val).all(-1)
Output/mask:输出/掩码:
array([[False, True, False],
[False, True, True],
[ True, False, False]]
Problem is that with bigger data
array and increasing number of tuples in filter_vals
, it is getting slower.问题是随着更大的data
数组和filter_vals
组数量的增加,它变得越来越慢。 It there any better solution?它有更好的解决方案吗? I tried to use np.isin(data, filter_vals)
, but it does not provide result I need.我尝试使用np.isin(data, filter_vals)
,但它没有提供我需要的结果。
A classical approach using broadcasting would be:使用广播的经典方法是:
*A, B = data.shape
(data.reshape((-1,B)) == np.array(filter_vals)[:,None]).all(-1).any(0).reshape(A)
This will however be memory expensive.然而,这将是 memory 昂贵。 So applicability really depends on your use case.所以适用性真的取决于你的用例。
output: output:
array([[False, True, False],
[False, True, True],
[ True, False, False]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.