Pythus Pythus - 2 months ago 7
Python Question

Copying and Modifying a Dataframe Pandas

I have 3 Dataframes df1,df,df3 all copying an original Dataframe df0.

df1=df0
df2=df0
df3=df0

df1=dfo.iloc[1:,1:].div(dfo.iloc[1:,1:].sum(axis=1),axis=0)
df2=dfo.iloc[1:,1:].div(dfo.iloc[1:,1:].sum(axis=1),axis=0)*ACCOUNT_CASH
df3=df2//df0

print(df1)
print(df2)
print(df3)


Somehow this does not work, I get no error but when I Print df1 df2 df3 all my dataframes are the same! However they're different from df0.Is it because they all point to the same space in memory, and so changing any pointer actually modifies all variables? If so how can I make it work well. I tried copy(deep=True) with unconclusive results. Thanks

Answer

Your lines

df1=df0
df2=df0
df3=df0

simply create three new bindings, where three new names refer to the same object as that bound to by df0.

To actually create copies, use pd.DataFrame.copy:

df1=df0.copy()
df2=df0.copy()
df3=df0.copy()
Comments