gpt4 book ai didi

python - 作为函数参数的 Pandas DataFrame - Python

转载 作者:太空宇宙 更新时间:2023-11-03 14:43:31 28 4
gpt4 key购买 nike

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

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

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

最佳答案

如果函数参数是一个可变对象(例如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 如何传递函数参数。

关于python - 作为函数参数的 Pandas DataFrame - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51391438/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com