I have the following dict, with keys as tuples:
JavaScript
x
2
1
d = {('first', 'row'): 3, ('second', 'row'): 1}
2
I’d like to create a dataframe with 3 columns: Col1, Col2 and Col3 which should look like this:
JavaScript
1
4
1
Col1 Col2 Col3
2
first row 3
3
second row 4
4
I can’t figure out how to split the tuples other than parsing the dict pair by pair.
Advertisement
Answer
Construct a Series first, then resetting the index will give you a DataFrame:
JavaScript
1
6
1
pd.Series(d).reset_index()
2
Out:
3
level_0 level_1 0
4
0 first row 3
5
1 second row 1
6
You can rename columns afterwards:
JavaScript
1
8
1
df = pd.Series(d).reset_index()
2
df.columns = ['Col1', 'Col2', 'Col3']
3
df
4
Out:
5
Col1 Col2 Col3
6
0 first row 3
7
1 second row 1
8
Or in one-line, first naming the MultiIndex:
JavaScript
1
6
1
pd.Series(d).rename_axis(['Col1', 'Col2']).reset_index(name='Col3')
2
Out[7]:
3
Col1 Col2 Col3
4
0 first row 3
5
1 second row 1
6