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

Pandas:如何让函数仅修改输入DataFrame的副本

如何避免修改作为函数输入的原始Pandas DataFrame?

你的问题出在:df_out = df只是给原始DataFrame起了个别名,并没有生成独立的副本,后续对df_out的修改会直接同步到原始的df_input上。

解决方法很简单,在函数内部先创建输入DataFrame的深副本,再基于副本做修改:

def new_func(df):
    df_out = df.copy()  # 创建独立副本,切断与原始数据的引用关联
    df_out['new'] = 'C'
    return df_out

测试修改后的函数:

df_input = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6]})
df_output = new_func(df_input)

# 原始DataFrame无新增列
print(df_input)
#    a  b
# 0  1  4
# 1  2  5
# 2  3  6

# 输出DataFrame包含新增列
print(df_output)
#    a  b new
# 0  1  4   C
# 1  2  5   C
# 2  3  6   C

如果你的DataFrame包含嵌套数据结构(比如列值是列表、字典),可以显式指定deep=True(默认就是该值,可省略),确保所有嵌套对象也被复制:

df_out = df.copy(deep=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 13:05:06