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!
CodePudding user response:
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}
CodePudding user response:
You can use pandas.at:
>>> df.at[1, 'DEF'] = dict1
>>> df
name DEF
0 L1 None
1 L2 {'DEF120': 50}
This way you can get the value 50
by doing:
>>> df.loc[df.name=='L2', 'DEF'].str['DEF120']
1 50
Name: DEF, dtype: int64
CodePudding user response:
You can try to pass dictionary as list or use np.where
or Series.mask
.
df.loc[df.name=='L2', 'DEF'] = [dict1]
# or
df['DEF'] = df['DEF'].mask(df.name=='L2', dict1)
# or
df['DEF'] = np.where(df.name=='L2', dict1, df['DEF'])
print(df)
name DEF
0 L1 None
1 L2 {'DEF120': 50}
CodePudding user response:
Basically you can do this like this:
import pandas as pd
dic = {"1st_entry":"hallo","2nd_entry":"good by"}
data = [1,2,3,dic]
df=pd.DataFrame(data)
print(df)
will result in
0
0 a
1 b
2 c
3 {'1st_entry': 'hallo', '2nd_entry': 'good by'}
You have to find the right method to enter the data