数据帧在子函数中被覆盖

dataframe is overwritten in subfunction

以下示例显示了在子函数中编辑数据框时出现的问题,但仅返回了其中的一部分

以下是代码作用的简要说明:

我不明白这一点,因为函数内的变量变化不应该影响函数外的值。

非常感谢您就如何避免这种行为提出意见。

import pandas as pd

def do_something(df):
    df['col3'] = df['col1']+df['col2'] # new column
    df['col1'] = 111 #some change
    df['col2'] = 222 #some change
    return df[['col3']].copy()


data = {"col1":[1, 2, 3], "col2":[4, 5, 6]}
df = pd.DataFrame(data)

df_new = do_something(df)
df.merge(df_new, how='left')


print('orginal df was modified by do_something')
print(df)

print('the return of the function do_something')
print(df_new)

这里是网上找的例子https://trinket.io/python3/3f273591fb

df的当前输出

   col1  col2  col3
0   111   222     5
1   111   222     7
2   111   222     9

df 的预期输出

   col1  col2  col3
0     1     4     5
1     2     5     7
2     3     6     9

回答

this is not a pandas issue, it's because of mutability

的评论中所述

您正在将原始对象的引用传递给函数,以便对原始对象进行编辑。 您必须将副本传递给您的函数。

使用:

df_new = do_something(df.copy())