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

Dict of DataFrames

Let’s say I initialize a df and then I assign it to a dict 3 times, each one with a specific key.

import pandas as pd

df = pd.DataFrame({'A': [2, 2], 'B': [2, 2]})

dict = {}

for i in range(3):
    dict_strat['Df {0}'.format(i)] = df

Alright, what I’m not understanding is that when I try to change value of one element in the dictionary, it changes all the others. For example:

dict_strat['Df 0'].iloc[0, :] = 9

It not only changes the first df on the dict, it changes all of them. Why? How can I get rid of that?

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

>Solution :

The DataFrames are all shallow copies, meaning that mutating one of them will mutate the others in the dictionary.

To resolve this issue, make deep copies using .copy(). You also should be using f-strings rather than .format():

for i in range(3):
    dict_strat[f'Df {i}'] = df.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