-1

I have written code where I have a dataframe containing all types of food. I have then split it into fruit and veg series using str.contains. I have written code where I append any food which is common in both series to a list:

fruit = fruit_2.tolist()#converting the series to a list
veg = veg_2.tolist()#converting the series to a list

for x in range (len(fruit)):
    for y in range (len(veg)):
        if fruit[x] == veg[y]:
            both.append(fruit[x]) 
print(both)

This works just wondering if someone has a solution which utilised pandas and doesn't use a for loop. Thanks

Harry Maguire
  • 153
  • 2
  • 10
  • Combine the two series and do: https://stackoverflow.com/questions/14657241/how-do-i-get-a-list-of-all-the-duplicate-items-using-pandas-in-python – xyzjayne Jul 18 '18 at 14:41
  • isin would be enough – mad_ Jul 18 '18 at 14:44
  • Possible duplicate of [Finding the intersection between two series in Pandas](https://stackoverflow.com/questions/18079563/finding-the-intersection-between-two-series-in-pandas) – moshevi Jul 18 '18 at 14:44
  • 1
    Possible duplicate of [How to implement 'in' and 'not in' for Pandas dataframe](https://stackoverflow.com/questions/19960077/how-to-implement-in-and-not-in-for-pandas-dataframe) – ALollz Jul 18 '18 at 14:48

2 Answers2

0

Try this:

fruit_2[fruit_2.isin(veg_2)]

This will give you the common elements.

Ashish Acharya
  • 3,349
  • 1
  • 16
  • 25
0

you could use np.intersect1d

import numpy as np

# gives a numpy array (you can later convert to series or list)
both = np.intersect1d(fruit_2, veg_2)  

courtesy of this answer

moshevi
  • 4,999
  • 5
  • 33
  • 50