首页 > 解决方案 > 带有计数器字典(多个键)的字典作为 2 列数据框

问题描述

我有一个二元字典,它被创建为

self.bigram_counts = defaultdict(lambda: Counter())

来自 self.bigram_counts 的 2 个样本行:

 [(None, Counter({'de': 1})),
 ('de', Counter({'la': 7839,filtradojardin': 1,'cantera': 236})))]

尝试如下将其加载到数据框中似乎效率低下:

bigrams2 = pd.DataFrame.from_dict(list((vocab.bigram_counts.keys(), 
                                       vocab.bigram_counts.values().keys()), 
                                       vocab.bigram_counts.values().values()))

我想要这个数据框中的 2 列,一个带有完整的二元组,一个带有计数。在这种情况下调用 pd.DataFrame 的最佳方法是什么?

以前,我用过:

bigrams = pd.DataFrame.from_dict(list(vocab.bigram_counts.items()))
bigrams.columns = [['word(s)', 'count(s)']]
bigrams.head()

哪个有效,但为计数列提供了一个计数器对象。我不认为 .melt() 就在这里,但也许可以使用类似的东西?

期望的输出:

     0    1
0    None, de            1
1    de, la           7839
2    de, filtradojardin  1
3    de, cantera       236

标签: pythonpandasdataframecounter

解决方案


我会做这样的事情:

flat_bigram_counts = (
    (word1, word2, count)
    for word1, counter in bigram_counts
    for word2, count in counter.items()
)
df = pd.DataFrame.from_records(flat_bigram_counts)

我的机器为您的示例中的两行输出以下内容:

      0               1     2
0  None              de     1
1    de              la  7839
2    de  filtradojardin     1
3    de         cantera   236

推荐阅读