问题:
我有几本词典,其中包含单词作为键和数字作为值,如下所示:
dict1 = {'foo':3, 'bar':1, 'world':6}
dict2 = {'foo':1, 'hello':4, 'world':12}
我想将它们放入一个空的数据框中,为每个原始单词创建一个新列并将数字存储在每个单元格中,如下所示:
| foo | bar | hello | world |
----|-------|-------|-------|-------|
0 | 3 | 1 | 0 | 6 |
----|-------|-------|-------|-------|
1 | 1 | 0 | 4 | 12 |
----|-------|-------|-------|-------|
解决方案尝试:
我目前正在定义一个函数,该函数每次调用时都会创建一行。我试过:
def fill_df(df, dict)
for key in dict:
df = df.append(wf, ignore_index=True)
我对此有几个问题。
- 首先:它只是完全跳过了这一点,我认为是因为列还不存在。我需要弄清楚如何根据
key
的值创建它们。 - 第二:我预测这会遇到多行的问题,因为许多键出现在某些
dicts
而不是其他中。我需要一种方法来说明,如果字典中不存在某个列的值,则该列在该行中的值应为0
。
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
您可以使用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