Skip to content
Advertisement

Set dictionary keys as cells in dataframe column

Please look at my code:

import pandas as pd

my_dict = {
1 :{'a':5 , 'b':10},
5 :{'a':6 , 'b':67},
7 :{'a':33 , 'b':9},
8 :{'a':21 , 'b':37},
}

df = pd.DataFrame (my_dict).transpose()
df['new'] = df.index

print (df)

Here I convert dictionary to DataFrame and set index as new column.

    a   b  new
1   5  10    1
5   6  67    5
7  33   9    7
8  21  37    8
   

Can it be done in 1 line at the stage of converting a dictionary to a date without

df['new'] = df.index

I want to immediately recognize the major indices as cells of the new column. Something like

df = pd.DataFrame (my_dict, 'new' = list(my_dict.keys()).transpose()

Advertisement

Answer

You can just reset_index() to create a column from index and df.rename to change name of index column to new

df = pd.DataFrame(my_dict).transpose().reset_index().rename(columns={"index": "new"})
print(df)
   new   a   b
0    1   5  10
1    5   6  67
2    7  33   9
3    8  21  37
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement