获取pandas merge中保留列的行索引



我目前使用pandas.merge查找两个不同熊猫帧之间的对齐行,如下所示:


import pandas as pd
import numpy as np
rng = pd.date_range('2015-02-24', periods=5, freq='T')
df_1 = pd.DataFrame({ 'timestamp': rng, 'Val': np.random.randn(len(rng)) })
df_1 = df_1.drop(df_1.index[[0]])
df_2 = pd.DataFrame({ 'timestamp': rng, 'Val': np.random.randn(len(rng)) })
df_2 = df_2.drop(df_2.index[[4]])
common_rows = pd.merge(df_1, 
df_2.reset_index(), 
how='inner', 
on=['timestamp'])

按预期工作,并给了我一个统一的pandas框架,但我想知道的是在两个数据框架中保留哪些行索引。我的需要是能够过滤掉两个数据框,只保留这些常见的行,而不是有这个统一的视图。

您可以继续使用您的方法,使用suffixes参数:

common_rows = pd.merge(df_1.reset_index(), 
df_2.reset_index(), 
how='inner', 
on=['timestamp'],
suffixes=['_1', '_2']
)
df_1 = df_1.loc[common_rows.index_1.unique()]
df_2 = df_2.loc[common_rows.index_2.unique()]

使用reindex保持共同行:

df_1 = df_1.set_index('timestamp') 
.reindex(df_2['timestamp']) 
.dropna(how='all') 
.reset_index()
df_2 = df_2.set_index('timestamp') 
.reindex(df_1['timestamp']) 
.reset_index()

输出:

>>> df_1
timestamp       Val
0 2015-02-24 00:01:00 -0.833354
1 2015-02-24 00:02:00 -1.445002
2 2015-02-24 00:03:00 -2.106964
>>> df_2
timestamp       Val
0 2015-02-24 00:01:00  0.863396
1 2015-02-24 00:02:00  0.263386
2 2015-02-24 00:03:00 -0.169489

最新更新