如何在Pandas中合并两个含整数的DataFrame并累加对应值
合并Pandas DataFrame并累加同名条目值
高效实现方案(推荐)
直接利用Pandas内置的concat和groupby方法,无需手动遍历,代码简洁且效率更高:
1. 构造示例数据
import pandas as pd # 现有余额DataFrame existing_balance = pd.DataFrame({ "Name": ["echo", "fives", "rex"], "Coins Won": [250, 250, 500] }) # 新存入DataFrame new_deposits = pd.DataFrame({ "Name": ["echo", "hunter", "kix"], "Coins Won": [500, 1000, 250] })
2. 合并并累加计算
# 合并两个DataFrame combined_data = pd.concat([existing_balance, new_deposits]) # 按Name分组,对Coins Won字段求和 final_result = combined_data.groupby("Name", as_index=False)["Coins Won"].sum()
3. 输出结果
最终final_result的内容如下:
| Name | Coins Won |
|---|---|
| echo | 750 |
| fives | 250 |
| hunter | 1000 |
| kix | 250 |
| rex | 500 |
兼容原有字典遍历的方案(不推荐,大数据量下效率低)
如果你想沿用自己的字典遍历逻辑,只需添加未匹配条目的判断与添加步骤:
existing_records = existing_balance.to_dict(orient="records") new_records = new_deposits.to_dict(orient="records") for new_entry in new_records: is_matched = False for existing_entry in existing_records: if existing_entry["Name"] == new_entry["Name"]: existing_entry["Coins Won"] += new_entry["Coins Won"] is_matched = True break # 找到匹配项后立即终止内层循环,减少不必要遍历 # 若当前新条目未在现有记录中找到匹配,直接追加 if not is_matched: existing_records.append(new_entry) # 将处理后的字典转回DataFrame result_df = pd.DataFrame(existing_records)
内容的提问来源于stack exchange,提问作者CodenameCanopy
相关产品推荐
相关产品推荐

