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

Abh*_*mar 2 html python csv python-3.x pandas

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

每当我尝试除打印整个数据框之外的任何内容时,我都面临如下错误。

print(dfdefault.shape())
AttributeError: 'list' object has no attribute 'shape'
Run Code Online (Sandbox Code Playgroud)

Coh*_*han 7

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
Run Code Online (Sandbox Code Playgroud)

从这里,您只需要指定要使用的表。如果只有一张桌子,很容易弄清楚要使用哪一张。

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)
Run Code Online (Sandbox Code Playgroud)