【问题标题】:Got KeyError for trying to loop a dictionary to get a counter尝试循环字典以获取计数器时遇到 KeyError
【发布时间】:2020-12-16 07:53:04
【问题描述】:

我正在 youtube 上进行一项练习,我试图在 csv 数据中获取字典计数器。 代码如下:

import pandas as pd
from collections import Counter

URL = 'https://raw.githubusercontent.com/CoreyMSchafer/code_snippets/master/Python/Matplotlib/02-BarCharts/data.csv'

data = pd.read_csv(url)
df = pd.DataFrame.to_dict(data)

language_counter = Counter()

for i in df:
     language_counter.update(df['LanguagesWorkedWith'][i].split(';'))

print(language_counter)

知道出了什么问题吗?这是显示的错误:

Traceback (most recent call last):
  File "C:/Users/jong5/PycharmProjects/learning/matplotlib/matplotlib-Bar.py", line 14, in <module>
    language_counter.update(df['LanguagesWorkedWith'][i].split(';'))
KeyError: 'Responder_id'

'Responder_id' 是第一个列名。 感谢任何帮助,谢谢!

【问题讨论】:

  • df['LanguagesWorkedWith'] 中不存在键“Responder_id”。我想这是一个字典。

标签: python dictionary counter


【解决方案1】:

没有熊猫

import requests
from collections import Counter

r = requests.get(
    'https://raw.githubusercontent.com/CoreyMSchafer/code_snippets/master/Python/Matplotlib/02-BarCharts/data.csv')
if r.status_code == 200:
    counter = Counter()
    text = r.text
    lines = text.split()
    for idx, line in enumerate(lines):
        if idx > 0:
            line = line.strip()
            comma_idx = line.find(',')
            counter.update(line[comma_idx:].split(';'))
    print(counter.most_common(5))

输出

[('JavaScript', 57290), ('SQL', 47272), ('HTML/CSS', 40015), ('Python', 34645), ('Java', 31019)]

【讨论】:

    【解决方案2】:

    在不需要迭代列时使用to_dict。请改用for column_value in data_frame['column_name']

    import pandas as pd
    from collections import Counter
    
    URL = 'https://raw.githubusercontent.com/CoreyMSchafer/code_snippets/master/Python/Matplotlib/02-BarCharts/data.csv'
    
    data = pd.read_csv(url)
    
    # remove this line
    # df = pd.DataFrame.to_dict(data)
    
    language_counter = Counter()
    
    # and select a column directly
    for lang in data['LanguagesWorkedWith']:
         language_counter.update(lang.split(';'))
    
    print(language_counter)
    

    【讨论】:

    • 正在尝试遍历“LanguagesWorkedWith”列下的字典值。尝试了这段代码并得到了错误:AttributeError: 'int' object has no attribute 'split'
    【解决方案3】:

    感谢各位的回复,玩了一圈终于找到了办法。对不起,如果我不清楚这些问题。 这是修改后的代码:

    for i in df['LanguagesWorkedWith']:
        language_counter.update(df['LanguagesWorkedWith'][i].split(';'))
    
    print(language_counter)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多