访问DataFrame列时出现KeyError: 'Topic Name'问题求助
问题排查:Pandas KeyError: 'Topic Name'
错误核心原因
代码中存在列名不匹配的问题:
- 在
scrape_topics()函数里,创建DataFrame时定义的标题列名为'Topic Title':
table_dict = { 'Topic Title': get_topic_titles(doc1), 'Topic Link': get_topic_urls(doc1), 'Topic Description': get_topic_description(doc1) }
- 但在
scrape_topics_repos()函数中,你尝试访问的列名是'Topic Name':
print('Scraping top repositories for "{}"'.format(row['Topic Name'])) scrape_topic(row['Topic Link'], 'data/{}.csv'.format(row['Topic Name']))
Pandas找不到对应列,因此抛出KeyError: 'Topic Name'。
修复方案
任选以下一种方式统一列名即可:
方式一:修改DataFrame的列名为'Topic Name'
调整scrape_topics()函数中的字典键名:
table_dict = { 'Topic Name': get_topic_titles(doc1), # 将'Topic Title'改为'Topic Name' 'Topic Link': get_topic_urls(doc1), 'Topic Description': get_topic_description(doc1) }
方式二:修改访问列的名称为'Topic Title'
调整scrape_topics_repos()函数中的代码:
def scrape_topics_repos(): print('Scraping list of topics') topics_df = scrape_topics() os.makedirs('data', exist_ok=True) for index, row in topics_df.iterrows(): print('Scraping top repositories for "{}"'.format(row['Topic Title'])) # 改为'Topic Title' scrape_topic(row['Topic Link'], 'data/{}.csv'.format(row['Topic Title'])) # 改为'Topic Title'
额外建议
为避免类似列名错误,可在创建DataFrame后添加列名打印代码,确认列名是否正确:
def scrape_topics(): # ... 原有代码 ... df = pd.DataFrame(table_dict) print("DataFrame列名:", df.columns.tolist()) # 打印列名用于校验 return df
内容的提问来源于stack exchange,提问作者Harshpreet Kaur
相关产品推荐
相关产品推荐

