Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas replace is executing over two separate dataframes

I’m trying to make a temporary dataframe where NaN values are replaced by zeros without affecting the original dataframe. However, I noticed that when I replace the NaN’s of df_2 with 0s the corresponding column in df_1 is also changed. Have I done something wrong here when creating df_2?

Code

d = {'A':[np.nan, np.nan],'B':[1,2]}
df_1 = pd.DataFrame(data=d)
df_2 = df_1
print(df_1)
print(df_2)
df_2['A'] = df_2['A'].replace(np.nan,0)
print(df_1)
print(df_2)

Outputs

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    A  B
0 NaN  1
1 NaN  2
    A  B
0 NaN  1
1 NaN  2

     A  B
0  0.0  1
1  0.0  2
     A  B
0  0.0  1
1  0.0  2

>Solution :

Use deep copy

df_2 = df_1.copy()

See more in pandas.DataFrame.copy

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading