2

Let's say I have a numpy array with the following shape :

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

I want to :

- Sort the array according to nonSortedNonFiltered[1] - Filter the array according to nonSortedNonFiltered[0] and an array of values

I currently do the sorting with :

sortedNonFiltered=nonSortedNonFiltered[:,nonSortedNonFiltered[1].argsort()]

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

Now I want to filter sortedNonFiltered from an array of values, for example :

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

Note : Each value in a column of my 2D array is exclusive.

1 Answer 1

2

You can use np.in1d to get a boolean mask and use it to filter columns in the sorted array, something like this -

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

Sample run -

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]])
Sign up to request clarification or add additional context in comments.

2 Comments

wow that's perfect ! I was implementing a loop but it was way too slow for my huge number of values. This works way better
@OdgyGsf Yes, np.in1d is quite efficient to solve cases like this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.