我正在从 URL(RSS 提要)中提取信息,以创建一个大数据框,其中包含情感分析所需的所有数据。我做了一个函数来获取字典中的每个 url,使用解析器,然后将条目放在数据帧上。 5 次迭代后,我收到错误:InvalidIndexError:重新索引仅对具有唯一值的 Index 对象有效。 我正在使用像 {'name': 'url'} 这样的字典,代码如下:
def extract_content(urls):
df_final = pd.DataFrame()
for url in urls.values():
xml = feedparser.parse(url)
entries = xml['entries']
df = pd.DataFrame(entries)
if 'media_content' in df.columns:
df.rename(columns = {'media_content': 'content'}, inplace = True)
if 'content' not in df.columns:
df.rename(columns={'summary': 'content'}, inplace=True)
df = df[['title', 'link', 'published', 'published_parsed', 'content']]
df_final = pd.concat([df_final, df]).reset_index(drop = True)
return df_final
我该如何修复它?
我尝试了reset_index()但仍然不起作用。
我认为它来自重复的列名。例如,以下代码会重现该错误:
df_final = pd.DataFrame({'A': [1, 2], 'B': [3,4]})
df = pd.DataFrame({'A': [1, 2], 'B': [5,5], 'C': [5, 6]})
df.rename(columns = {'C': 'A'}, inplace=True)
df = df[['A', 'B']]
df_final = pd.concat([df_final, df]).reset_index(drop = True)
df_final
在此代码中,我首先将 DataFrame df 中的“C”列重命名为“A”列。即使已经存在名为“A”的列,它在重命名期间也不会抛出任何错误,但由于重复的列名,它会在串联期间抛出错误“InvalidIndexError:重新索引仅对具有唯一值的索引对象有效”。我认为当您将列“media_content”重命名为列名称“content”时,您的情况就会发生这种情况。您尚未检查列名“content”是否已存在于 DataFrame df 中。如果列名“content”已经存在,则会在串联过程中产生报告的错误。 我在这里看到两种可能的解决方案:
解决方案1您在串联之前删除重复的列:
df_final = pd.DataFrame({'A': [1, 2], 'B': [3,4]})
df = pd.DataFrame({'A': [1, 2], 'B': [5,5], 'C': [5, 6]})
df.rename(columns = {'C': 'A'}, inplace=True)
df = df[['A', 'B']]
df = df.loc[:,~df.columns.duplicated()]
df_final = pd.concat([df_final, df]).reset_index(drop = True)
df_final
这会毫无错误地输出预期的输出(我们只保留第一列名称“A”):
A B
0 1 3
1 2 4
2 1 5
3 2 5
仅当 DataFrame df 中不存在所需名称作为列名称时,才重命名列:
df_final = pd.DataFrame({'A': [1, 2], 'B': [3,4]})
df = pd.DataFrame({'A': [1, 2], 'B': [5,5], 'C': [5, 6]})
if 'A' not in df.columns:
df.rename(columns = {'C': 'A'}, inplace=True)
df = df[['A', 'B']]
df_final = pd.concat([df_final, df]).reset_index(drop = True)
df_final