【问题标题】:Python function behaves unexpectedly [duplicate]Python函数行为异常[重复]
【发布时间】:2017-11-20 19:56:43
【问题描述】:

我正在使用函数对 pandas 数据框进行非常简单的转换,但我没想到该函数会更改输入数据框(但确实如此)。我想知道为什么...

这是我的代码:

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

def transform(df, increment):
    new_df = df
    new_df.a = new_df.a + increment
    return new_df

new_x = transform(x, 1)

new_x # output shows new_x.a is [2,3,4], which is expected.
x # output shows x.a is also [2,3,4]. I thought it should be [1,2,3]

为什么会这样?我认为,在函数中,所有操作都在new_df 上执行,所以输入x 在我运行这个transform 函数之前和之后应该保持完全相同,不是吗?

【问题讨论】:

  • new_df = df not 复制数据帧。您只需对 same 对象进行另一个引用。
  • 是的,new_df 和 df 是同一个对象的两个名称。
  • new_df = df.copy()

标签: python function pandas


【解决方案1】:

这是因为它不会创建副本,而是x 的另一个“引用” 对象

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


def transform(df, increment):
    new_df = df.copy() # <--- piece to change
    new_df.a = new_df.a + increment
    return new_df

new_x = transform(x, 1)

new_x # output shows new_x.a is [2,3,4], which is expected.
x # output shows x.a is now [1,2,3].

当您添加 .copy() 时,这将为您提供预期的行为

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-23
    • 1970-01-01
    • 2019-12-02
    • 1970-01-01
    • 1970-01-01
    • 2015-08-27
    • 2021-05-17
    相关资源
    最近更新 更多