Reputation: 21
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.
key
.dicts
and not others. I need a way to say that, if there's no value for a certain column present in the dictionary, then that column should have a value of 0
in that row.Upvotes: 0
Views: 1276
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
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