Python AssertionError:传递了5列,传递的数据有1列

Python AssertionError:传递了5列,传递的数据有1列,python,pandas,dataframe,Python,Pandas,Dataframe,这是我的密码 from bs4 import BeautifulSoup import pandas as pd import requests link1 = 'https://en.wikipedia.org/wiki/List_of_United_States_counties_by_per_capita_income' page1 = requests.get(link1) soup1 = BeautifulSoup(page1.text) table = soup1.find_al

这是我的密码

from bs4 import BeautifulSoup
import pandas as pd
import requests

link1 = 'https://en.wikipedia.org/wiki/List_of_United_States_counties_by_per_capita_income'
page1 = requests.get(link1) 
soup1 = BeautifulSoup(page1.text)
table = soup1.find_all('table')[1]
table_rows = table.find_all('tr')
res = []
for tr in table_rows:
    td = tr.find_all('td')
    row = [tr.text.strip() for tr in td if tr.text.strip()]
    if row:
        res.append(row)
df_state = pd.DataFrame(res, columns=["Rank", "Country-equivalent", "State", "Per capita income", "Population"])
df_state.head()

错误出现在最后一行,非常感谢您的帮助。

以下是您的期望:

from bs4 import BeautifulSoup
import pandas as pd
import requests

link1 = 'https://en.wikipedia.org/wiki/List_of_United_States_counties_by_per_capita_income'
page1 = requests.get(link1) 
soup1 = BeautifulSoup(page1.text)
table = soup1.find_all('table')[2]
table_rows = table.find_all('tr')
res = []
for tr in table_rows:
    td = tr.find_all('td')
    row = [tr.text.strip() for tr in td if tr.text.strip()]
    if row:
        res.append(row)
df_state = pd.DataFrame(res, columns=["Rank", "Country-equivalent", "State", "Per capita income", "Population", "temp1", "temp2", "temp3"])
df_state.head()
第一个变化是第9行:我在
soup1.find_all('table')
中查找索引2而不是1


第二个问题是,在数据帧的初始化过程中,我们为您提供了5列,其中有8列。我添加了
“temp1”、“temp2”、“temp3”

以下是
res
的前两个元素的可能重复:
[['这篇文章是关于']的系列文章的一部分,['主题\nHousehold\n个人\nAffluence\n社会阶层\nIncome不平等性\ngender pay gap\nHnic wage gap']
。我不认为这是对的。是的,这很好。非常感谢。但是你能解释一下问题是什么吗?