0

In Python, I have a list of different size arrays. I would like to know the intersection for all arrays contained in the list. For instance:

import numpy as np

array0 = [0,1,2,3,4,5,6]
array1 = [0,2,3,5,6,7,8,9,10]
array2 = [4,5,6]
array3 = [5,6,7,8,9,10,11,12,13]

array_list = [array0, array1, array2, array3]

I want to use a function like np.intersect1d across all of the arrays in array_list and get the intersection across all data arrays. From a quick glance, the answer would be

intersection = np.array([5,6])

I've tried using list comprehension, something like:

np.intersect1d([arraylist[x] for x in np.arange(len(arraylist))]),

but Numpy expects 2 arguments instead of the one I'm providing. For a similar reason,

list(filter(lambda x:x in [x for x in arraylist]))

will not work -- filter expects 2 arguments, and is only getting one.

AaronJPung
  • 1,105
  • 1
  • 19
  • 35
  • Does this answer your question? [What is a best way to intersect multiple arrays with numpy array?](https://stackoverflow.com/questions/59656759/what-is-a-best-way-to-intersect-multiple-arrays-with-numpy-array) – Woodford Aug 18 '23 at 18:50

1 Answers1

2

you can use reduce() from functools module to intersect multiple lists with np.intersect1d:

import numpy as np
from functools import reduce

array0 = [0,1,2,3,4,5,6]
array1 = [0,2,3,5,6,7,8,9,10]
array2 = [4,5,6]
array3 = [5,6,7,8,9,10,11,12,13]

array_list = [array0, array1, array2, array3]

print(reduce(np.intersect1d,[array0, array1, array2, array3] ))

output:-

[5 6]

or use sets to intersect them

import numpy as np

array0 = [0,1,2,3,4,5,6]
array1 = [0,2,3,5,6,7,8,9,10]
array2 = [4,5,6]
array3 = [5,6,7,8,9,10,11,12,13]
    
array_list = [array0, array1, array2, array3]

print(set.intersection(*map(set,array_list)))

output:-

{5,6}
vegan_meat
  • 878
  • 4
  • 10