Pandas DataFrame 作为函数的参数 - Python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51391438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:49:00  来源:igfitidea点击:

Pandas DataFrame as an Argument to a Function - Python

pythonpandasfunctiondataframeparameter-passing

提问by WhiteDillPickle

Suppose a Pandas DataFrame is passed to a function as an argument. Then, does Python implicitly copy that DataFrame or is the actual DataFrame being passed in?

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

Hence, if I perform operations on the DataFrame within the function, will I be changing the original (because the references are still intact)?

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

I just want to know whether or not I should make a Deep Copy of my DataFrame before passing it into a function and operating on it.

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

回答by aydow

If a function parameter is not an immutable object (e.g. a DataFrame), then any changes you make in the function will be applied to the object.

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

E.g.

例如

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

See thisarticle for a good explanation on how Python passes function parameters.

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