处理网页中的空单元格

2024-04-20 08:35:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从篮球参考表(http://www.basketball-reference.com/leagues/NBA_2015_per_poss.html)中获取所有数据。当我使用XPath获取数据时,它作为一个长列表出现。我有一个“chunks”方法,可以将列表划分为多个列表,但是,由于表中有空单元格,因此该方法会出错并错误地划分列表。有什么办法解决这个问题吗


Tags: 数据方法comhttp列表htmlwwwxpath
1条回答
网友
1楼 · 发布于 2024-04-20 08:35:41

我的建议是:使用pandas.DataFrame。它可以从许多源加载数据,包括HTML

您可以使用fillna方法轻松地处理空单元格

考虑这个例子:

import pandas as pd

# read_excel returns list of dataframes.
# In this case we know there is only one in the page
df = pd.read_html('http://www.basketball-reference.com/leagues/NBA_2015_per_poss.html',
                  attrs={'id': 'per_poss'})[0] 

# the headers repeat every 20 lines, filtering them out
df = df[df['Rk'] != 'Rk'] 

# inserting 0 to empty cells
# could also use inplace=True kwarg instead of reassigning, or pass a 
# dictionary to use different value for each column 
df = df.fillna(0) 

相关问题 更多 >