如何从 pandas 系列元素中获取 "aggregate" 字数

How to get "aggregate" word count from pandas Series elements

我目前在带有 pandas 0.23.4 的 Jupyter Notebook (v5.6.0) 中使用 python3.7。

我编写了代码来标记一些日语单词,并成功应用了一个单词计数函数,returns 单词从 pandas 系列中的每一行开始计数,如下所示:

0       [(かげ, 20), (モリア, 17), (たち, 15), (お前, 14), (おれ,...
1       [(お前, 11), (ゾロ, 10), (うっ, 10), (たち, 9), (サンジ, ...
2       [(おれ, 11), (男, 6), (てめえ, 6), (お前, 5), (首, 5), ...
3       [(おれ, 19), (たち, 14), (ヨホホホ, 12), (お前, 10), (みん...
4       [(ラブーン, 32), (たち, 14), (おれ, 12), (お前, 12), (船長...
5       [(ヨホホホ, 19), (おれ, 13), (ラブーン, 12), (船長, 11), (...
6       [(わたし, 20), (おれ, 16), (海賊, 9), (お前, 9), (もう, 9...
7       [(たち, 21), (あたし, 15), (宝石, 14), (おれ, 12), (ハッ,...
8       [(おれ, 13), (あれ, 9), (もう, 7), (ヨホホホ, 7), (見え, 7...
9       [(ケイミー, 23), (人魚, 20), (はっち, 14), (おれ, 13), (め...
10      [(ケイミー, 18), (おれ, 17), (め, 14), (たち, 12), (はっち... 

来自这个先前提出的问题:

Creating a dictionary of word count of multiple text files in a directory

我想我可以使用答案来帮助我 objective。

我想将每一行中的所有上述对合并到一个字典中,其中键是日语文本,值是数据集中出现的所有文本实例的总和。我想我可以使用 collections.Counter 模块通过将系列中的每一行变成字典来完成此操作,如下所示:

vocab_list = []
for i in range(len(wordcount)):
    vocab_list.append(dict(wordcount[i]))

这给了我想要的字典格式,系列中的每一行现在都是一个字典,如下所示:

[{'かげ': 20,
 'モリア': 17,
 'たち': 15,
 'お前': 14,
 'おれ': 11,
 'もう': 9,
 '船長': 7,
 'っ': 7,
 '七武海': 7,
 '言っ': 6, ...

当我尝试使用 sum() 函数和 Counter() 来汇总总数时,我的问题就来了:

vocab_list = sum(vocab_list, Counter())
print(vocab_list)

我没有得到预期的 "aggregated dictionary",而是收到以下错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-37-3c66e97f4559> in <module>()
      3     vocab_list.append(dict(wordcount[i]))
      4 
----> 5 vocab_list = sum(vocab_list, Counter())
      6 vocab_list

TypeError: unsupported operand type(s) for +: 'Counter' and 'dict'

您能解释一下代码中到底有什么问题以及如何解决吗?

我不熟悉 Counter(),但我认为这可能与您的字典在列表中有关。

此外,您无需使用其他工具(如计数器)即可轻松完成此操作。这是我放在一起 'works' 但可能无法在您的用例中执行的内容:

vocab_list = [{'かげ': 20,
            'モリア': 17,
            'たち': 15,
            'お前': 14,
            'おれ': 11,
            'もう': 9,
            '船長': 7}]

numberz = list(vocab_list[0].values())
totalz = 0
for x in numberz:
    totalz += x

print(totalz)

Out [29]: 93

如果您系列中的元素属于 Counter 类型,您可以简单地通过 sum

进行聚合
df.agg(sum)

示例:

from collections import Counter

df = pd.Series([[('かげ', 20), ('男', 17), ('たち', 15), ('お前', 14)],[('お前', 11), ('ゾロ', 10), ('うっ', 10), ('たち', 9)],[('おれ', 11), ('男', 6), ('てめえ', 6), ('お前', 5), ('首', 5)]])   
df = df.apply(lambda x: Counter({y[0]:y[1] for y in x}))

df
# Out:
# 0          {'かげ': 20, '男': 17, 'たち': 15, 'お前': 14}
# 1          {'お前': 11, 'ゾロ': 10, 'うっ': 10, 'たち': 9}
# 2    {'おれ': 11, '男': 6, 'てめえ': 6, 'お前': 5, '首': 5}
# dtype: object

df.agg(sum)
# Out:
# Counter({'うっ': 10,
#          'おれ': 11,
#          'お前': 30,
#          'かげ': 20,
#          'たち': 24,
#          'てめえ': 6,
#          'ゾロ': 10,
#          '男': 23,
#          '首': 5})