繁体   English   中英

比较两个数据框的日期列并保持具有相同日期的行

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

我有两个数据帧 df1 和 df2,我想保留每个数据帧中包含与另一个数据帧相同日期的行:

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

期望的输出:

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

首先将日期列作为索引,然后执行以下操作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM