I have two numpy arrays

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jenya56
    New Member
    • Nov 2009
    • 14

    I have two numpy arrays

    of not equal length. How to find the elements that are both in array1 and array2? Thanks!!!
  • Glenton
    Recognized Expert Contributor
    • Nov 2008
    • 391

    #2
    Sounds like a job for sets.
    See docs here

    Code:
    In [21]: a
    Out[21]: array([1, 2, 3, 4])
    
    In [22]: b
    Out[22]: array([2, 4, 4, 5, 5])
    
    In [23]: a2=set(a)
    
    In [24]: b2=set(b)
    
    In [25]: a2
    Out[25]: set([1, 2, 3, 4])
    
    In [26]: b2
    Out[26]: set([2, 4, 5])
    
    In [27]: result = a2 & b2 #or a2.intersection(b2)
    
    In [28]: result
    Out[28]: set([2, 4])
    Or you could loop through one of the arrays and check whether it's in the other.
    Code:
    In [29]: for i in a:
       ....:     if i in b:
       ....:         print i,
       ....:         
       ....:         
    2 4

    Comment

    Working...