Please look at my code:
JavaScript
x
14
14
1
import pandas as pd
2
3
my_dict = {
4
1 :{'a':5 , 'b':10},
5
5 :{'a':6 , 'b':67},
6
7 :{'a':33 , 'b':9},
7
8 :{'a':21 , 'b':37},
8
}
9
10
df = pd.DataFrame (my_dict).transpose()
11
df['new'] = df.index
12
13
print (df)
14
Here I convert dictionary to DataFrame and set index as new column.
JavaScript
1
7
1
a b new
2
1 5 10 1
3
5 6 67 5
4
7 33 9 7
5
8 21 37 8
6
7
Can it be done in 1 line at the stage of converting a dictionary to a date without
JavaScript
1
2
1
df['new'] = df.index
2
I want to immediately recognize the major indices as cells of the new column. Something like
JavaScript
1
2
1
df = pd.DataFrame (my_dict, 'new' = list(my_dict.keys()).transpose()
2
Advertisement
Answer
You can just reset_index()
to create a column from index and df.rename
to change name of index
column to new
–
JavaScript
1
3
1
df = pd.DataFrame(my_dict).transpose().reset_index().rename(columns={"index": "new"})
2
print(df)
3
JavaScript
1
6
1
new a b
2
0 1 5 10
3
1 5 6 67
4
2 7 33 9
5
3 8 21 37
6