How to convert the dictionary with one key and a tuple as the key value into a DataFrame?

Viewed 28

I have a dictionary like this.

dict={'good': (5, 3, 5), 'nice': (6, 0, 0), 'very': (8, 3, 4), 'not': (2, 0, 1)}

I need to convert it into a dataframe such that it looks like this:

Variable     Positive Neutral Negative
good           5       3       5
nice           6       0       0
very           8       3       4
not            2       0       1

I tried using:

pd.DataFrame(dict).melt()

But it is giving me the data frame in the following form:

Variable Value

good      5
good      3
good      5
nice      6
nice      0
nice      0
... 

Please help me get the required output.

1 Answers

You can pass an index to pd.DataFrame and then take Tranpose:

pd.DataFrame(d, index=["Positive", "Neutral", "Negative"]).T

or swapaxes:

pd.DataFrame(d, index=["Positive", "Neutral", "Negative"]).swapaxes(0, 1)

where d is your dictionary,

to get

      Positive  Neutral  Negative
good         5        3         5
nice         6        0         0
very         8        3         4
not          2        0         1
Related