python - Slice numpy array based on x number of other arrays -
i trying make current code dynamic. meaning should able adjust regardless of number of array inputs of 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) , np.in1d(array2, my_list2)]
the desired result of printing out result_array
is:
array([1, 4])
this because of intersection of a
, cat & b
, cat
.
my goal able n number of array1
, array2
... , n number of my_list1
, my_list2
...
thanks in advance!
version more 2 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) 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 2 arrays only.
this should work:
my_arrays = [array1, array2] my_lists = [my_list1, my_list2] main1[np.logical_and(*(np.in1d(array, lst) array, lst in zip(my_arrays, my_lists)))]
result:
array([1, 4])
Comments
Post a Comment