I have the following dict, with keys as tuples:
d = {('first', 'row'): 3, ('second', 'row'): 1}
I’d like to create a dataframe with 3 columns: Col1, Col2 and Col3 which should look like this:
Col1 Col2 Col3 first row 3 second row 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:
pd.Series(d).reset_index() Out: level_0 level_1 0 0 first row 3 1 second row 1
You can rename columns afterwards:
df = pd.Series(d).reset_index() df.columns = ['Col1', 'Col2', 'Col3'] df Out: Col1 Col2 Col3 0 first row 3 1 second row 1
Or in one-line, first naming the MultiIndex:
pd.Series(d).rename_axis(['Col1', 'Col2']).reset_index(name='Col3') Out[7]: Col1 Col2 Col3 0 first row 3 1 second row 1