gpt4 book ai didi

python - 在这种情况下,Python 是按引用传递还是按值传递,为什么?

转载 作者:行者123 更新时间:2023-12-02 00:59:05 24 4
gpt4 key购买 nike

以下代码是我的简单示例,对于每一步,我都会在注释中解释我在做什么,问题在最后。

import pandas as pd
todays_date = datetime.datetime.now().date()
index = pd.date_range(todays_date, periods=3, freq='D')
columns = ['A','B','C']
df1 = pd.DataFrame(index=index, columns=columns)
df1 = df1.fillna(1)

# up to here, i've just create a random df1, which looks like the follow:
# A B C
# 2020-03-24 1 1 1
# 2020-03-25 1 1 1
# 2020-03-26 1 1 1

df2 = df1 # here created a copy of df1 named as df2, it should pass by value based on my knowledge
df1 += df2.shift(1) # this should be the same as df1 = df1 + df2.shift(1)

display(df1) # here I print out df1 which looks like the follow:
# A B C
# 2020-03-24 NaN NaN NaN
# 2020-03-25 2.0 2.0 2.0
# 2020-03-26 2.0 2.0 2.0

display(df2) # here I print out df2, the result surprise me because i thought df2 isn't changed from when it is defined , however it becomes the same as the new df1:
# A B C
# 2020-03-24 NaN NaN NaN
# 2020-03-25 2.0 2.0 2.0
# 2020-03-26 2.0 2.0 2.0

谁能向我解释一下为什么df2这些步骤有变化吗?我真的很困惑。

最佳答案

df2 = df1     # here created a copy of df1 named as df2

该评论不正确,可能是造成您误解的原因。

这行代码的意思是:df2 现在是当前称为 df1 的另一个名称。

因此,如果您更改名为 df1 的对象,当您引用 df2 时,您也会看到此更改。

关于python - 在这种情况下,Python 是按引用传递还是按值传递,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60829498/

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