Skip to content
Advertisement

How to convert dictionary values as rows under each column?

df1:
Id   Rick  Nick  Tom  Jerry
101  2000  3000  4000 6500
101  5000  9000  8000 2500
101  6000  8000  6000 6300

Dict1= {Rick:G-1, Nick:G-2, Tom:G-3, Jerry:G-4}

df_output:

Id   Rick  Nick  Tom  Jerry
Desc G-1   G-2   G-3  G-4
101  2000  3000  4000 6500
101  5000  9000  8000 2500
101  6000  8000  6000 6300

I need to map Dictionary with Column Names & it should come just below the Headers

Advertisement

Answer

Try something like creating a df and appending:

(pd.Series(Dict1).to_frame().T
 .append(df,sort=False).fillna({"Id":"Desc"}).loc[:,df.columns])

Or:

pd.concat((pd.DataFrame.from_dict(Dict1,orient='index').T,
           df),sort=False).fillna({"Id":"Desc"}).reindex(df.columns,axis=1)

     Id  Rick  Nick   Tom Jerry
0  Desc   G-1   G-2   G-3   G-4
0   101  2000  3000  4000  6500
1   101  5000  9000  8000  2500
2   101  6000  8000  6000  6300
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement