Compare Dataframes Based on Column and Keep only common rows present in both dataframes

Viewed 28

I am having two dataframes df1& df2 as below.

import pandas as pd
data1 = [['1', 11], ['2', 12], ['3', 13],['5', 18],['8', 19]]
df1 = pd.DataFrame(data1, columns=['Strike', 'Price'])
df1

Output-

    Strike  Price
0   1   11
1   2   12
2   3   13
3   5   18
4   8   19

data2 = [['1', 10], ['2', 15], ['4', 14],['8', 18]]
df2 = pd.DataFrame(data2, columns=['Strike', 'Price'])
df2

Strike  Price
0   1   10
1   2   15
2   4   14
3   8   18

I want to compare column Strike of df1 & df2 and keep only rows which are having comman values present in Strike column of both df1,df2 and reset index of both dataframes.

Expected Output-

df1
    Strike  Price
0   1   11
1   2   12
2   8   19

df2
Strike  Price
0   1   10
1   2   15
2   8   18
2 Answers

Try this;

df3 = df1.merge(df2["Strike"],on="Strike",how="inner")
df4 = df2.merge(df1["Strike"],on="Strike",how="inner")

df3 & df4 are the outputs of df1 & df2 respectively.

search df1 within df2 and then use location to identify the rows

df1.loc[df1['Strike'].isin(df2['Strike'])]
Strike  Price
0   1   11
1   2   12
4   8   19

same as above, just switch df1 with df2

df2.loc[df2['Strike'].isin(df1['Strike'])]
    Strike  Price
0   1   10
1   2   15
3   8   18
Related