简体   繁体   English

如何通过公共列(ID)将两个分组熊猫数据帧合并在一起?

[英]How to merge two grouped-by Pandas Dataframes by a common column(ID) together?

I'm learning data analysis with pandas. 我正在学习熊猫数据分析。

I have two grouped-by dataframes, looking like below. 我有两个按数据分组的数据框,如下所示。

df1: df1:

        count1  count2  rate
id          
958     34  34  1.000000
2822    41  41  1.000000
5193    180 184 0.978261
5841    35  35  1.000000
5858    104 104 1.000000

df2: df2:

    price
id  
958     170
2822    138
5193    160
5841    181
5858    250

How can I do pd.merge(df1, df2, how='inner', on=['id']) ? 我该怎么办pd.merge(df1, df2, how='inner', on=['id']) Currently, since 'id' is the index, I can't select it. 目前,由于“ id”是索引,因此无法选择它。 Could someone help? 有人可以帮忙吗?

You could use join 您可以使用join

In [226]: df1.join(df2)
Out[226]:
      count1  count2      rate  price
id
958       34      34  1.000000    170
2822      41      41  1.000000    138
5193     180     184  0.978261    160
5841      35      35  1.000000    181
5858     104     104  1.000000    250

or merge by using reset_index of df1 , df2 或通过使用df1df2 reset_index进行merge

In [227]: pd.merge(df1.reset_index(), df2.reset_index(), how='inner', on=['id'])
Out[227]:
     id  count1  count2      rate  price
0   958      34      34  1.000000    170
1  2822      41      41  1.000000    138
2  5193     180     184  0.978261    160
3  5841      35      35  1.000000    181
4  5858     104     104  1.000000    250

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

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