python - pd.read_html(url) - 尴尬的表格设计

标签 python pandas

整个表格的表格标题正在转换为单列标题。

url = "https://www.environment.nsw.gov.au/topics/animals-and-plants/threatened-species/programs-legislation-and-framework/nsw-koala-strategy/local-government-resources-for-koala-conservation/north-coast-koala-management-area#:~:text=The%20North%20Coast%20Koala%20Management,Valley%2C%20Clarence%20Valley%20and%20Taree."
dfs = pd.read_html(url)
df = dfs[0]
df.head()

output

如果我可以将高度首选用途用作分配给正确物种的列,那就太好了。 尝试了reset_index()这不起作用。 我因搜索找不到类似的内容而迷失了方向。

回复@Master Oogway 并感谢@DYZ 的编辑。

有多个“table-striped”

Screen shot inspect element - multiple class ="table-striped"

建议的修正消除了错误,但不与第二个表交互。 以白盒白桉为例。出现在第二个表中而不是第一个表中。 如果我导出 dftable 并过滤 - 无白盒:

Filter no White Box

如果我在使用 find_all 和搜索时将 htmltable 写入 .txt,它就在那里:

enter image description here

我以前从未这样做过,并且意识到这很烦人。 感谢您迄今为止的帮助。

看来 find_all 正在收集所有表数据。 但 dftable 的创建仅限于第一个“table-striped”。

最佳答案

该表无法使用 read_html 轻松解析因为它非正统地使用 <thead>属性。您可以用BeautifulSoup试试运气。 :

import bs4
import urllib.request

soup = bs4.BeautifulSoup(urllib.request.urlopen(url))
data = [["".join(cell.strings).strip() 
         for cell in row.find_all(['td', 'th'])] 
         for row in soup.find_all('table')[0].find_all('tr')]    
table = pd.DataFrame(data[1:])\
          .rename(columns=dict(enumerate(data[0])))\
          .dropna(how='all')

关于python - pd.read_html(url) - 尴尬的表格设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74596303/

相关文章:

python - 理解 "item for item in list_a if ..."Python

python - 使用 pathos ProcessingPool 的映射时如何设置 block 大小?

python - 如何使用例如将 MS Access 表导出到 Python 中的 csv 文件pypyodbc

python - 根据特定的月份值和以另一列为条件过滤 Pandas 数据框

python - 将 NaN 转换为 DataFrame 中的数字时出现 TyperError

python - 从 pandas apply() 函数中获取前一行值

python - 使用 python 脚本打开 localhost 端口

python - 使用 eclipse 运行 Python Django migrate 时出现 Mysql 错误

python - Pandas DataFrame 中的点表示法是如何实现的?

python - 将列表列表中的数据添加到数据框的自己的行中