【问题标题】:Pandas read_html returned column with NaN values in PythonPandas read_html 在 Python 中返回具有 NaN 值的列
【发布时间】:2019-06-15 08:34:00
【问题描述】:
我正在尝试使用 Pandas read.html 函数解析位于 here 的表。我能够解析表格。但是,使用 NaN 返回的列容量。我不确定,可能是什么原因。我想解析整个表格并将其用于进一步研究。所以任何帮助表示赞赏。以下是我到目前为止的代码..
wiki_url='Above url'
df1=pd.read_html(wiki_url,index_col=0)
【问题讨论】:
标签:
python
html
pandas
html-parsing
wikipedia
【解决方案1】:
Pandas 只能获取上标(无论出于何种原因)而不是实际值,如果您打印所有 df1 并检查容量列,您会看到其中一些值是 [1]、[2]等(如果有脚注),否则为 NaN。
您可能想研究获取数据的替代方法,或者自己使用 BeautifulSoup 抓取数据,因为 Pandas 正在查找并因此返回错误的数据。
【解决方案2】:
尝试这样的事情(包括flavor 为bs4):
df = pd.read_html(r'https://en.wikipedia.org/wiki/List_of_NCAA_Division_I_FBS_football_stadiums',header=[0],flavor='bs4')
df = df[0]
print(df.head())
Image Stadium City State \
0 NaN Aggie Memorial Stadium Las Cruces NM
1 NaN Alamodome San Antonio TX
2 NaN Alaska Airlines Field at Husky Stadium Seattle WA
3 NaN Albertsons Stadium Boise ID
4 NaN Allen E. Paulson Stadium Statesboro GA
Team Conference Capacity \
0 New Mexico State Independent 30,343[1]
1 UTSA C-USA 65000
2 Washington Pac-12 70,500[2]
3 Boise State Mountain West 36,387[3]
4 Georgia Southern Sun Belt 25000
.............................
.............................
要替换方括号内的任何内容,请使用:
df.Capacity = df.Capacity.str.replace(r"\[.*\]","")
print(df.Capacity.head())
0 30,343
1 65000
2 70,500
3 36,387
4 25000
希望这会有所帮助。
【解决方案3】:
@anky_91 发布的答案是正确的。我想在不使用 Regex 的情况下尝试另一种方法。以下是我不使用正则表达式的解决方案。
df4=pd.read_html('https://en.wikipedia.org/wiki/List_of_NCAA_Division_I_FBS_football_stadiums',header=[0],flavor='bs4')
df4 = df4[0]
解决办法是去掉@anky_91在第1行和第4行提出的“r”
print(df4.Capacity.head())
0 30,343
1 65000
2 70,500
3 36,387
4 25000
Name: Capacity, dtype: object