【问题标题】:Creating a separate Counter() object and Pandas DataFrame for each list within a list of lists为列表列表中的每个列表创建单独的 Counter() 对象和 Pandas DataFrame
【发布时间】:2016-03-29 22:34:29
【问题描述】:

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

我目前有一个列表列表:

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]]

我想通过循环为每个列表返回一个字典或 Counter() 对象:

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

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

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})

上面的问题是我似乎无法找到一种单独获取每个 Counter 的方法,因为我正在尝试为这些字典/计数器对象中的每一个创建一个 pandas 数据框。我正在尝试以编程方式执行此操作,因为我的“master_list”中有数百个列表,我想返回一个数据框,显示每个单独列表的元素频率。最后,我将为“主列表”中的每个列表提供一个单独的数据框和计数器对象

目前我有一些只返回 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() 对象的技巧都将不胜感激。

【问题讨论】:

  • 你到底指的是什么?

标签: python pandas dataframe counter nested-lists


【解决方案1】:

IMO,这个问题可以显示真正的熊猫的力量。让我们执行以下操作 - 而不是计算无聊的[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],我们将计算真实书籍中单词的频率。我选择了以下三个:“浮士德”、“哈姆雷特”、“麦克白”。

代码:

#!/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

【讨论】:

    【解决方案2】:

    您可以创建一个列表并将计数器附加到它。 (另外,您正在使用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] 处理每个单独的列表。

    【讨论】:

    • 这行得通,谢谢。我从来没有意识到字典列表是一个完美的数据结构。
    猜你喜欢
    • 2021-08-31
    • 1970-01-01
    • 2015-03-09
    • 1970-01-01
    • 1970-01-01
    • 2019-08-31
    • 2015-01-31
    • 2020-10-18
    相关资源
    最近更新 更多