pandas - 在数值相同的情况下将两个数据框相加

3

我有两个单词计数的数据框,假设第一个数据框是...

    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)

但这就是我所知道的。任何帮助都将不胜感激。
3个回答

3
你可以合并数据框并求和。
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

2
你也可以使用append和groupby来使用这个一行代码得到结果 -
df_1.append(df_2).groupby('word', as_index=False).sum()

1
你可以使用以下步骤:首先使用pandas.merge将数据框合并。然后对两个count列进行求和,最后使用fillna来填充NaN
df3 = pd.merge(df1, df2, on='word', how='outer', suffixes=['', '_2'])

df3['count'] = df3['count'].fillna(0) + df3['count_2'].fillna(0)
df3['count'].fillna(df3['count_2'], inplace=True)
df3.drop('count_2', axis=1, inplace=True)

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接