Home > Net >  Common elements in two dataframe
Common elements in two dataframe

Time:11-09

Having two data frame as below:

data frame:1

new_data = {
  "Fruits": ['AB', 'AB','BC', 'CD','DE','EG'],
  "price": [50, 30, 45,55,47,43]
}
new_df = pd.DataFrame(new_data)

print(new_df) 

dataframe:2

import pandas as pd

data = {
  "Food": ['AB','AB','BC', 'CE','DE','EF','EM','FB'],
  "Calories": [150, 405, 450,55,47,43,43,23]
}

#load data into a DataFrame object:
df = pd.DataFrame(data)

print(df) 

need to return the unique values in dataframe1, comparing with the food column in dataframe2.

Expected output

 Fruit  Price
0    AB     50
1    AB     30
2    BC     45
3    DE     47

return the first dataframe where the food values is in fruit value

CodePudding user response:

You can use .loc[] with .isin() to check if a value in the Fruits from new_df exist in the Food column of df:

new_df.loc[new_df['Fruits'].isin(df['Food'])]

  Fruits  price
0     AB     50
1     AB     30
2     BC     45
4     DE     47
  • Related