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

时间:2015-08-04 12:31:20

标签: python arrays numpy

我们说我有一个具有以下形状的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

注意:我的2D数组的列中的每个值都是独占的。

1 个答案:

答案 0 :(得分:2)

您可以使用np.in1d获取布尔掩码并使用它来过滤已排序数组中的列,如下所示 -

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

示例运行 -

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]])