You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Pandas实现DataFrame更新并按需追加行?

Pandas合并DataFrame:保留所有索引并覆盖重复值

你可以用以下两种方法实现需求:

方法1:使用combine_first()

这个方法会优先采用df2的数值覆盖重复索引,同时保留df1里独有的行,最终包含两个DataFrame的所有索引。

示例代码:

import pandas as pd

# 构建原始数据
df1 = pd.DataFrame({'column': ['A1', 'A2']}, index=[1, 2])
df2 = pd.DataFrame({'column': ['A2_new', 'A3']}, index=[2, 3])

# 生成结果
result_df = df2.combine_first(df1)
print(result_df)

输出结果:

column
index        
1          A1
2      A2_new
3          A3

方法2:使用concat + groupby

先把两个DataFrame纵向拼接,再按索引分组取每组最后一条数据(因为df2放在拼接顺序的后面,重复索引的最后一条就是df2的数值)。

示例代码:

result_df = pd.concat([df1, df2]).groupby(level=0).last()
print(result_df)

为什么update()不行?

df1.update(df2)只会修改df1中已存在的索引对应的值,不会新增df2里独有的索引行(比如索引3),所以满足不了你的需求。

内容的提问来源于stack exchange,提问作者Ars ML

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 01:32:14