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

标签 python html python-3.x pandas csv

我正在将 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/

相关文章:

python - blockmanage() 采用 1 个位置参数,但在将数组传递给函数时给出了 36 个位置参数

javascript - 使用 Jquery 警报对话框插件进行链接确认

python-3.x - 如何使用带有 urllib 的 urlopen 修复 Python 3 中的 HTTP 错误

Python - 正则表达式,列表末尾的空白元素?

python - 找不到 Sdl2-config 错误(安装 pygame_sdl2)

python - Tkinter 菜单栏插入位置 0 不起作用

python - 无法从 django 中的 GET 字典获取所有值

javascript - fontawesome onclick 图标使用 Material 表更改 Angular

javascript - 在数据表中呈现嵌套行的最佳方法是什么?

python - Django:无法在指定中间模型的 ManyToManyField 上设置值