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

Write dictionary inside a DataFrame as an element

Is it possible to write a dictionary into Data Frame? I have created the following DataFrame with my structure:

df =pd.DataFrame({'name': ['L1', 'L2'], 'DEF': [None, None]})

df
Out[70]: 
  name   DEF
0   L1  None
1   L2  None

I also have a dictionary

dict1={'DEF120':50}

If try to write dictionary into df as

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

df.loc[df.name=='L2', 'DEF'] = dict1

I am getting NaN as

df
Out[76]: 
  name   DEF
0   L1  None
1   L2   NaN

But! If I write a random number, then it works!

df.loc[df.name=='L2', 'DEF'] = 1323213

df
Out[78]: 
  name      DEF
0   L1     None
1   L2  1323213

Can someone please explain what is the problem here? Why does writing dictionary not work?

Thanks!

>Solution :

Dictionaries/lists have a special meaning when assigned using loc. Pandas will try to expand them to Series.

You need to cheat a bit and use at:

s = df.name=='L2'
idx = s[s].index[0]
df.at[idx, 'DEF'] = dict1

updated dataframe:

  name             DEF
0   L1            None
1   L2  {'DEF120': 50}
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