2

I have the following 2 arrays:

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

 ids = np.array([6, 5, 7, 8])

Each row in the array arr describes a 4-digit id, there are no redundant ids - neither in their values nor their combination. So if [1, 2, 3, 4] exists, no other combination of these 4 digits can exist. This will be important in a sec.

The array ids contains a 4-digit id, however the order might not be correct. Now I need to go through each row of arr and look if this id exists. In this example ids fits to the 2nd row from the top of arr. So arr[1,:].

My current solution creates a filter of each column to check if the values of ids exist in any of the 4 columns. After that I use these filters on arr. This seems way too complicated.

So I pretty much do this:

 filter_1 = np.in1d(arr[:, 0], ids)
 filter_2 = np.in1d(arr[:, 1], ids)
 filter_3 = np.in1d(arr[:, 2], ids)
 filter_4 = np.in1d(arr[:, 3], ids)

 result = arr[filter_1 & filter_2 & filter_3 & filter_4]

Does anyone know a simpler solution? Maybe using generators?

1 Answer 1

1

Use np.isin all across arr and all-reduce to get result -

In [15]: arr[np.isin(arr, ids).all(1)]
Out[15]: array([[5, 6, 7, 8]])
Sign up to request clarification or add additional context in comments.

1 Comment

Cheers, this is way more elegant.

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.