为列表列表中的每个列表创建一个单独的 Counter() 对象和 Pandas DataFrame

Creating a separate Counter() object and Pandas DataFrame for each list within a list of lists

我能找到的所有其他答案都特别提到了聚合列表列表中的所有嵌套列表,而我希望为每个列表单独聚合。

我目前有列表列表:

master_list = [[a,a,b,b,b,c,c,c], [d,d,d,a,a,a,c,c,c], [c,c,c,a,a,f,f,f]]

我想 return 一个字典或每个带有循环的列表的 Counter() 对象:

counter1 = {'a': 2, 'b': 3, 'c': 3}
counter2 = {'d': 3, 'a': 3, 'c': 3}
counter3 = {'c': 3, 'a': 2, 'f': 3}

目前,我正在 return 使用循环来创建看起来像这样的东西 - 这并不是我想要的,因为它们全部集中在一起,而且我无法单独访问计数器对象:

Input:

count = Counter()
for lists in master_list:
    for words in lists:
    count[words] += 1


Output:

Counter({'a': 2, 'b': 3, 'c': 3})
Counter({'d': 3, 'a': 3, 'c': 3})
Counter({'c': 3, 'a': 2, 'f': 3})

上面的问题是我似乎无法找到一种方法来单独获取每个计数器,因为我正在尝试为其中的每个 [=31] 创建一个 pandas 数据框=] 对象。我正在尝试以编程方式执行此操作,因为我的 "master_list" 中有数百个列表,我想 return 一个显示每个单独列表的元素频率的数据框。最后,我将为 "master-list"

中的每个列表创建一个单独的数据框和计数器对象

目前我有一些东西 return 只有 1 个数据帧:

Input:

table = pandas.DataFrame(count.items())
table.columns = ['Word', 'Frequency']
table.sort_values(by=['Frequency'], ascending = [False])


Output:

Word   Frequency
the    542
and    125
or     45
.      .
.      .
.      .
.      .

任何见解将不胜感激 - 此外,任何关于单独处理 Counter() 对象的提示将不胜感激。

您可以创建一个列表并将计数器附加到它。 (此外,您正在使用 Counter,但仍在自己进行计数,这是不必要的。)

master_list = [[a,a,b,b,b,c,c,c], [d,d,d,a,a,a,c,c,c], [c,c,c,a,a,f,f,f]]
counters = []
for list_ in master_list:
    counters.append(Counter(list_))

现在您可以使用 counters[i] 来处理每个单独的列表。

IMO,这道题可以看出pandas真正的威力。让我们执行以下操作 - 我们将计算真实书籍中单词的出现频率,而不是计算无聊的 [a,a,b,b,b,c,c,c], [d,d,d,a,a,a,c,c,c], [c,c,c,a,a,f,f,f]。我选择了以下三个:'Faust'、'Hamlet'、'Macbeth'.

代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from collections import defaultdict
import string
import requests
import pandas as pd

books = {
  'Faust': 'http://www.gutenberg.org/cache/epub/2229/pg2229.txt',
  'Hamlet': 'http://www.gutenberg.org/cache/epub/2265/pg2265.txt',
  'Macbeth': 'http://www.gutenberg.org/cache/epub/2264/pg2264.txt',
}

# prepare translate table, which will remove all punctuations and digits
chars2remove = list(string.punctuation + string.digits)
transl_tab = str.maketrans(dict(zip(chars2remove, list(' ' * len(chars2remove)))))
# replace 'carriage return' and 'new line' characters with spaces
transl_tab[10] = ' '
transl_tab[13] = ' '


def tokenize(s):
    return s.translate(transl_tab).lower().split()

def get_data(url):
    r = requests.get(url)
    if r.status_code == requests.codes.ok:
        return r.text
    else:
        r.raise_for_status()

# generate DF containing words from books
d = defaultdict(list)
for name, url in books.items():
    d[name] = tokenize(get_data(url))

df = pd.concat([pd.DataFrame({'book': name, 'word': tokenize(get_data(url))})
                for name, url in books.items()], ignore_index=True)

# let's count the frequency
frequency = df.groupby(['book','word']) \
              .size() \
              .sort_values(ascending=False)

# output
print(frequency.head(30))
print('[Macbeth]: macbeth\t', frequency.loc['Macbeth', 'macbeth'])
print('[Hamlet]: nay\t', frequency.loc['Hamlet', 'nay'])
print('[Faust]: faust\t', frequency.loc['Faust', 'faust'])

输出:

book     word
Hamlet   the      1105
         and       919
Faust    und       918
Hamlet   to        760
Macbeth  the       759
Hamlet   of        698
Faust    ich       691
         die       668
         der       610
Macbeth  and       602
Hamlet   you       588
         i         560
         a         542
         my        506
Macbeth  to        460
Hamlet   it        439
Macbeth  of        426
Faust    nicht     426
Hamlet   in        409
Faust    das       403
         ein       399
         zu        380
Hamlet   that      379
Faust    in        365
         ist       363
Hamlet   is        346
Macbeth  i         344
Hamlet   ham       337
         this      328
         not       316
dtype: int64

[Macbeth]: macbeth      67
[Hamlet]: nay    27
[Faust]: faust   272