python - 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)
但这就是我所知道的。任何帮助表示赞赏。
解决方案
您可以合并数据框并求和,
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
推荐阅读
- r - 为什么数据表列表上的名称向量返回列表类型?
- java - Heroku 找不到主类:MainView
- apache-spark - 在 Pyspark 中使用 reduceByKey 方法更新字典
- swiftui - SwiftUI - NavigationLink 未在正确位置触发
- angular - 延迟加载模块会挂起 Angular Web 应用程序
- android - 从 Firestore 获取图像到 RecyclerView Android Studio
- javascript - 将数组从多个值简化为更少
- python - Python 会话不适用于多个请求
- c# - 通用赋值操作
- angular - 如何在 Cloud Firestore 中执行嵌套查询?