Bondrak
Bondrak

Reputation: 1590

Converting a python 3 dictionary into a dataframe (keys are tuples)

I have a dictionary that has the following structure:

Dict [(t1,d1)] = x

(x are integers, t1 and d1 are strings)

I want to convert this Dictionary into a dataframe of the following format:

   d1 d2 d3 d4
t1  x y  z  x
t2  etc.
t3
t4
...

The following command

d.DataFrame([[key,value] for key,value in Dict.items()],columns=["key_col","val_col"])

gives me

key_col val_col

0 (book, d1) 100

1 (pen, d1) 10

2 (book, d2) 30

3 (pen, d2) 0

How do I make d's my column names and t's my row names?

Upvotes: 1

Views: 83

Answers (1)

piRSquared
piRSquared

Reputation: 294218

Pandas automatically assumes tuple keys are multiindex. Pass dictionary to series constructor and unstack.

pd.Series(dct).unstack()

Upvotes: 2

Related Questions