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
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}