Pandas DataFrame 作为函数的参数 - Python

Whi*_*kle 6 python function parameter-passing dataframe pandas

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

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

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

ayd*_*dow 13

如果函数参数不是不可变对象(例如 a 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
Run Code Online (Sandbox Code Playgroud)

请参阅文章对Python的传递函数参数一个很好的解释。

  • 数据帧是*可变的*,而不是*不可变的* (6认同)