2

I am trying to make my current code dynamic. Meaning it should be able to adjust regardless of the number of array inputs of the user.

Current code:

main1 = numpy.array([1,2,3,4])
array1 = numpy.array(['a','b','c','b'])
my_list1 = ['a','b']
array2 = numpy.array(['cat','dog','bird','cat'])
my_list2 = ['cat']

result_array = main1[np.in1d(array1, my_list1) and np.in1d(array2, my_list2)]

The desired result of printing out result_array is:

array([1, 4])

This is because of the intersection of a and cat & b and cat.

My goal is to be able to do this with an n number of array1, array2 ... and n number of my_list1, my_list2...

Thanks in advance!

1 Answer 1

1

Version for more than two arrays, using logical_and.reduce:

array3 = numpy.array(['cat3','dog3','bird3','cat3'])
my_list3 = ['cat3']

my_arrays = [array1, array2, array3]
my_lists = [my_list1, my_list2, my_list3]
res1 = main1[numpy.logical_and.reduce(tuple(np.in1d(array, lst) for 
                                            array, lst in zip(my_arrays, my_lists)))]

Test it:

res2 = main1[np.in1d(array1, my_list1) & np.in1d(array2, my_list2) &
             np.in1d(array3, my_list3)]

Looks good:

>>> np.all(res1 == res2)
True

Old answer two arrays only.

This should work:

my_arrays = [array1, array2]
my_lists = [my_list1, my_list2]
main1[np.logical_and(*(np.in1d(array, lst) for array, lst in zip(my_arrays, my_lists)))]

Result:

array([1, 4])
Sign up to request clarification or add additional context in comments.

2 Comments

Works perfectly! Thanks a lot!
Hi! I thought it was working with three arrays and three lists but apparently it only considers up to the second pair of array-lists. How can we make the np.logical_and consider more than 2 arguments?

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.