Python 尝试附加数据帧时出现值错误
ValueError:传递值的长度为4,索引表示3Python 尝试附加数据帧时出现值错误,python,pandas,Python,Pandas,ValueError:传递值的长度为4,索引表示3 import requests from bs4 import BeautifulSoup import pandas as pd url_wiki = 'https://pt.wikipedia.org/wiki/Lista_dos_distritos_de_S%C3%A3o_Paulo_por_popula%C3%A7%C3%A3o' response = requests.get(url_wiki) soup = Beautif
import requests
from bs4 import BeautifulSoup
import pandas as pd
url_wiki = 'https://pt.wikipedia.org/wiki/Lista_dos_distritos_de_S%C3%A3o_Paulo_por_popula%C3%A7%C3%A3o'
response = requests.get(url_wiki)
soup = BeautifulSoup(response.text, "html.parser")
table = soup.find('table', {'class':'wikitable sortable'}).tbody
rows = table.find_all('tr')
columns= [v.text.replace('\n', '') for v in rows[0].find_all('th')]
print(columns)
'#columns has 3 elements!!'
df=pd.DataFrame(columns=columns)
#now have to populate the table
for i in range (1,len(rows)): #find skipping the first row, search in all rows
tds=rows[i].find_all('td')
#inspect ...rowspan 2 td tags, otherwise 3 td tags
if len(tds) == 2:
values = [tds[0].text.replace('\n', ''), tds[1].text.replace('\n', ''), tds[2].text.replace('\n', '')]
else:
values=[td.text.replace('\n', '') for td in tds]
#print(values)
到目前为止一切都很好
当我运行下面的行时,我得到了错误。检查上面的注释,索引有3个元素
此外,通过在上面运行#print(values),可以清楚地看到该表有3列
我错过了什么
df=df.append(pd.Series(values, index=columns), ignore_index=True)
df
回溯
---------------------------------------------------------------------------
ValueError回溯(最近一次调用上次)
在里面
---->1 df=df.append(pd.Series(值,索引=列),ignore_index=True)
e:\Anaconda3\lib\site packages\pandas\core\series.py in\uuuuuu init\uuuuuuu(self、data、index、dtype、name、copy、fastpath)
319试试:
320如果长度(索引)!=len(数据):
-->321上升值错误(
322 f“传递值的长度为{len(data)},”
323 f“索引意味着{len(索引)}。”
ValueError:传递值的长度为4,索引意味着3。
谢谢@Prune和@goalie1998。
实现并解决了问题。原始表中有一个“bug”,最后一个空行中有一个隐藏列。
通过在此处减去1来解决此问题:
对于范围(1,len(行)-1)中的i:#查找跳过第一行,搜索所有行
Cheers您缺少的是(1)完整的错误消息(包括回溯);(2)再现问题的最小代码;(3)在错误点跟踪问题值。表的最后一行有4列。您可以调整代码以忽略最后一列,也可以直接编辑源代码(通常不是一个选项,但它是维基百科…)。