gpt4 book ai didi

python - 如何读取 Pandas 中的html表并输出到数据框而不是列表

转载 作者:行者123 更新时间:2023-12-01 21:57:14 25 4
gpt4 key购买 nike

我正在将 html 文件中的 html 表读取到 pandas 中,并希望将其作为数据框而不是列表获取,以便我可以执行一般的数据框操作。

每当我尝试除了打印整个数据帧之外的任何事情时,我都会遇到如下错误。

print(dfdefault.shape())
AttributeError: 'list' object has no attribute 'shape'

最佳答案

Pandas .read_html() 函数将返回一个数据框列表,其中每个数据框都是在页面上找到的一个表格。使用 StackOverflow 的联赛,我们可以看到页面右侧有两个表格。如下所示,read_html() 返回的是一个列表。

url = 'https://stackexchange.com/leagues/1/alltime/stackoverflow'
df_list = pd.read_html(url)
print(df_list)
# [ Rep Change* Users <-- first table
# 0 10,000+ 15477
# 1 5,000+ 33541
# 2 2,500+ 68129
# 3 1,000+ 155430
# 4 500+ 272683
# 5 250+ 429742
# 6 100+ 458600
# 7 50+ 458600
# 8 1+ 458600,
# Total Rep* Users <-- second table
# 0 100,000+ 697
# 1 50,000+ 1963
# 2 25,000+ 5082
# 3 10,000+ 15477
# 4 5,000+ 33541
# 5 3,000+ 56962
# 6 2,000+ 84551
# 7 1,000+ 155430
# 8 500+ 272683
# 9 200+ 458600
# 10 1+ 10381503]

print(len(df_list))
# 2

在这里,您只需指定要使用的表。如果只有一张表,很容易找出使用哪一张。

df = df_list[0]
print(df)
# Rep Change* Users
# 0 10,000+ 15477
# 1 5,000+ 33541
# 2 2,500+ 68129
# 3 1,000+ 155430
# 4 500+ 272683
# 5 250+ 429742
# 6 100+ 458600
# 7 50+ 458600
# 8 1+ 458600
print(df.shape)
# (9, 2)

关于python - 如何读取 Pandas 中的html表并输出到数据框而不是列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55938023/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com