Molly Taylor
Molly Taylor

Reputation: 21

Fill empty dataframe with multiple dictionaries

Problem:

I have several dictionaries containing words as keys and numbers as values, like below:

dict1 = {'foo':3, 'bar':1, 'world':6}
dict2 = {'foo':1, 'hello':4, 'world':12}

I'd like to place them into an empty data frame, creating a new column for each original word and storing the number in each cell, like this:

    |  foo  |  bar  | hello | world |
----|-------|-------|-------|-------|
 0  |   3   |   1   |   0   |   6   |
----|-------|-------|-------|-------|
 1  |   1   |   0   |   4   |   12  |
----|-------|-------|-------|-------|

Solution Attempt:

I'm currently working to define a function that creates one row each time it's called. I've tried:

def fill_df(df, dict)
    for key in dict:
        df = df.append(wf, ignore_index=True)

I have a couple issues with this.

Upvotes: 0

Views: 1276

Answers (2)

BENY
BENY

Reputation: 323326

dict_list = [dict1, dict2]

df=pd.DataFrame(dict_list).fillna(0)
   foo  bar  world  hello
0    3  1.0      6    0.0
1    1  0.0     12    4.0

Upvotes: 2

Abbas
Abbas

Reputation: 643

You can directly append your dictonary by using df.append(dict, df.fillna(0),ignore_index=True).

df = df.append([dict1, dict2], ignore_index=True).fillna(0)
   foo  bar  world  hello
0    3  1.0      6    0.0
1    1  0.0     12    4.0

Upvotes: 0

Related Questions