Search code examples
pythonpandasdataframedictionarynested

nested dictionary --> dataframe with multi - columns


kdict = {'A': {'a': 1, 'b': 2}, 'B': {'a': 3, 'b': 4}, 'C': {'a': 5, 'b': 6}}

df5 = pd.DataFrame.from_dict(kdict, orient='index').stack()
df5.columns = ['a', 'b', 'a', 'b', 'a', 'b']
print(df5)

enter image description here

but i want to get the result, as below --

enter image description here

how can i get this form, as above ?


Solution

  • You can try to convert the Series to DataFrame and transpose:

    print(df5.to_frame().T)
    

    Prints:

       A     B     C   
       a  b  a  b  a  b
    0  1  2  3  4  5  6