问题描述
美好的一天,
我需要一些建议,我有两个数据框。一个包含数百行,另一个包含六行。时间戳为两帧编入索引。我想将 df1 中的索引值与 df2 进行比较,并仅保留与 df2 中的时间戳匹配的行。
GET
所以只有第 0、3 和 4 行应该留在 d1 中
解决方法
确保您的“日期-时间”列是两者中的 index
(您可以通过 set_index()
获取它,然后选择 1:
1) 使用 isin
:
df1_new = df1[df1.index.isin(df2.index)]
2) 使用 loc
:
df1_new = df1.loc[df2.index,:]
,
将您的索引更改为列,然后按照以下链接中的说明进行操作,之后您可以将其更改回索引
Compare two pandas dataframe with different size
,如果 Date-Time
是一列,试试这个:
df1 = df1[ df1['Date-Time'] == df2['Date-Time'] ]
您也可以通过合并数据框来实现:
df1 = pd.merge(df2['Date-Time'],df1,on='Date-Time',how='left')
,
这应该可以
df1.loc[df1.index.isin(df2.index)]