【问题标题】:Pandas DataFrame as an Argument to a Function - PythonPandas DataFrame 作为函数的参数 - Python
【发布时间】:2018-12-25 17:59:02
【问题描述】:

假设将 Pandas DataFrame 作为参数传递给函数。那么,Python 是隐式复制该 DataFrame 还是传入了实际的 DataFrame?

因此,如果我在函数内对 DataFrame 执行操作,我是否会更改原始数据(因为引用仍然完好无损)?

我只想知道是否应该在将 DataFrame 传递给函数并对其进行操作之前对其进行深度复制。

【问题讨论】:

标签: python pandas function dataframe parameter-passing


【解决方案1】:

如果函数参数不是不可变对象(例如DataFrame),那么您在函数中所做的任何更改都将应用于该对象。

例如

In [200]: df = pd.DataFrame({1:[1,2,3]})

In [201]: df
Out[201]:
   1
0  1
1  2
2  3

In [202]: def f(frame):
     ...:     frame['new'] = 'a'
     ...:

In [203]: f(df)

In [204]: df
Out[204]:
   1 new
0  1   a
1  2   a
2  3   a

请参阅this 文章,了解有关 Python 如何传递函数参数的详细说明。

【讨论】:

  • 数据帧是可变的,而不是不可变的
  • @PaulH 也许说 DataFrame 是 not 不可变(=可变)对象的示例