Skip to main content
 首页 » 编程设计

python之从值数组中过滤 2D numpy 数组

2024年10月24日14shanyou

假设我有一个具有以下形状的 numpy 数组:

nonSortedNonFiltered=np.array([[9,8,5,4,6,7,1,2,3],[1,3,2,6,4,5,7,9,8]]) 

我想:

- 根据 nonSortedNonFiltered[1] 对数组进行排序 - 根据 nonSortedNonFiltered[0] 和值数组过滤数组

我目前使用 :

进行排序
sortedNonFiltered=nonSortedNonFiltered[:,nonSortedNonFiltered[1].argsort()] 

给出:np.array([[9 5 8 6 7 4 1 3 2],[1 2 3 4 5 6 7 8 9]])

现在我想从值数组中过滤 sortedNonFiltered,例如:

sortedNonFiltered=np.array([[9 5 8 6 7 4 1 3 2],[1 2 3 4 5 6 7 8 9]]) 
listOfValues=np.array([8 6 5 2 1]) 
...Something here... 
 
> np.array([5 8 6 1 2],[2 3 4 7 9]) #What I want to get in the end 

注意:我的二维数组的一列中的每个值都是互斥的。

请您参考如下方法:

您可以使用 np.in1d获取一个 bool 掩码并使用它来过滤排序数组中的列,就像这样 -

output = sortedNonFiltered[:,np.in1d(sortedNonFiltered[0],listOfValues)] 

sample 运行-

In [76]: nonSortedNonFiltered 
Out[76]:  
array([[9, 8, 5, 4, 6, 7, 1, 2, 3], 
       [1, 3, 2, 6, 4, 5, 7, 9, 8]]) 
 
In [77]: sortedNonFiltered 
Out[77]:  
array([[9, 5, 8, 6, 7, 4, 1, 3, 2], 
       [1, 2, 3, 4, 5, 6, 7, 8, 9]]) 
In [78]: listOfValues 
Out[78]: array([8, 6, 5, 2, 1]) 
 
In [79]: sortedNonFiltered[:,np.in1d(sortedNonFiltered[0],listOfValues)] 
Out[79]:  
array([[5, 8, 6, 1, 2], 
       [2, 3, 4, 7, 9]])