作为2列数据帧的带计数器字典(多个键)的字典

2024-10-04 05:32:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本大字字典,它是作为

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

来自的2个样本行self.bigram\u计数地址:

 [(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()))

我想从这个数据帧中拿出两列,一列是完整的二元RAM,另一列是计数。打电话最好的方式是什么pd.数据帧在这种情况下?你知道吗

以前,我用过:

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

它可以工作,但为count列提供了一个counter对象。我不认为.melt()就在这里,但也许可以使用类似的东西?你知道吗

期望输出:

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

Tags: 数据selfnonecounterdelapd计数
1条回答
网友
1楼 · 发布于 2024-10-04 05:32:36

我会这样做:

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

相关问题 更多 >