尝试循环字典以获取计数器时出现KeyError

2024-10-02 04:22:40 发布

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

我在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”是第一个列名。 谢谢你的帮助,谢谢


Tags: csvinimportiddfdatamatplotlibcounter
3条回答

谢谢你的回复,在玩过之后,我终于找到了办法。对不起,如果我不清楚这些问题。 以下是修改后的代码:

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

print(language_counter)

没有熊猫

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

不需要在列上迭代时使用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)

相关问题 更多 >

    热门问题