Blg Khalil
Blg Khalil

Reputation: 349

Comparing the Date Columns of Two Dataframes and Keeping the Rows with the same Dates

I have two dataframes df1 and df2, I would like to keep the rows in each dataframe containing the same dates as the other one:

df1
>  Date     Price  Volume
0  2002-01-04   100    200
1  2002-01-05   200    400
2  2002-01-06   300    600
3  2002-01-07   400    800
4  2002-01-08   500    1000
5  2002-01-09   600    1200
6  2002-01-10   700    1400
df2
>  Date     Price  Volume
0  2002-01-04   100    200
1  2002-01-05   200    400
2  2002-01-06   300    600
3  2002-01-07   400    800
4  2002-01-09   500    1000
5  2002-01-11   600    1200
6  2002-01-12   700    1400
7  2002-01-13   800    1600

Desired output:

df1
>  Date     Price  Volume
0  2002-01-04   100    200
1  2002-01-05   200    400
2  2002-01-06   300    600
3  2002-01-07   400    800
5  2002-01-09   600    1200
df2
>  Date     Price  Volume
0  2002-01-04   100    200
1  2002-01-05   200    400
2  2002-01-06   300    600
3  2002-01-07   400    800
4  2002-01-09   500    1000

Upvotes: 0

Views: 917

Answers (1)

Saravanan Natarajan
Saravanan Natarajan

Reputation: 375

First make the date column as index and then do the following:

common_index = set(df1.index).intersection(df2.index)
df1 = df1.loc[common_index].copy()
df2 = df2.loc[common_index].copy()

Upvotes: 1

Related Questions