<分区>
尝试通过函数调用了解变量作用域。
要讨论的代码。
import numpy as np
import pandas as pd
# Function to add a column with random stuff to a dataframe
def Add_a_column(df):
df['Col2']= np.sign(np.random.randn(len(df)))
return df
# Create a dataframe with random stuff
df_full = pd.DataFrame(data=np.sign(np.random.randn(5)), columns=['Col1'])
df_another = Add_a_column(df_full)
- df_full 是全局的。正确吗?
- df_another 是全局的。正确吗?
- df 对于 Add_a_column 是本地的。正确吗?
当我执行代码时,该列被添加到 df_full
In[8]: df_full
Out[8]:
Col1 Col2
0 -1.0 -1.0
1 1.0 -1.0
2 -1.0 1.0
3 1.0 1.0
4 1.0 1.0
如何避免 df_full 被函数修改?