首页 > 解决方案 > pandas - 将两个数据框添加在一起,其中值相同

问题描述

我有两个字数数据框,假设第一个是...

    word   count
0   HELLO  8
1   MORE   10
2   HELP   19
3   NO     100

第二个是...

     word    count
0    HELLO   10
1    MORE    12
2    NONE    20
3    NO      56

结果应该是...

     word    count
0    HELLO   18
1    MORE    22
2    HELP    19
2    NONE    20
3    NO      156

顺序无关紧要。但我必须确保所有文字都被保留。如果两个数据帧中都存在这个词,我们将计数相加。如果另一个中不存在一个,我们只需添加它。

我想出了如何添加两个数据框...

df_add = df1.add(df2, fill_value=0)

但这就是我所知道的。任何帮助表示赞赏。

标签: pythonpandas

解决方案


您可以合并数据框并求和,

new_df = df1.merge(df2, on = 'word', how = 'outer')
new_df['count'] = new_df[['count_x', 'count_y']].sum(1)
new_df.drop(['count_x', 'count_y'], 1, inplace = True)

    word    count
0   HELLO   18.0
1   MORE    22.0
2   HELP    19.0
3   NO      156.0
4   NONE    20.0

推荐阅读