Geo
Geo

Reputation: 175

DataFrame from dict of lists with column values being keys

Suppose we have the following dict:

things = {'George':['cat','kitty'], 'Stackoverflow':['questions','answers'], 'hungry':['im','always']}

One could easily turn this into a list containing [[key1,value1]...[keyX,valueX]] and turn this into a dataframe that appears as: (index and column names ignored here)

George          cat 
George          kitty
Stackoverflow   questions 
Stackoverflow   answers
hungry          im
hungry          always

However, is this possible to be one directly from a dictionary?

Upvotes: 4

Views: 238

Answers (2)

user3483203
user3483203

Reputation: 51165

Simply use melt

pd.DataFrame(things).melt()

        variable      value
0         George        cat
1         George      kitty
2  Stackoverflow  questions
3  Stackoverflow    answers
4         hungry         im
5         hungry     always

If you want column names here, just use the var_name and value_name flags:

pd.DataFrame(things).melt(var_name='foo', value_name='bar')

Upvotes: 2

sacuL
sacuL

Reputation: 51335

You could do this using from_dict, and .stack:

pd.DataFrame.from_dict(things, orient='index').stack().reset_index(level=0)

         level_0          0
0         George        cat
1         George      kitty
2  Stackoverflow  questions
3  Stackoverflow    answers
4         hungry         im
5         hungry     always

Upvotes: 2

Related Questions