【问题标题】:How do I extract a specific column from a dataset using pandas that's imported from a HTML file?如何使用从 HTML 文件导入的 pandas 从数据集中提取特定列?
【发布时间】:2021-11-21 03:55:42
【问题描述】:
import requests
import os
import pandas as pd
from bs4 import BeautifulSoup

#Importing html
df = pd.read_html(os.path.expanduser("~/Documents/HTMLSpider/HTMLSpider_test/spotgamma.html"))
print (df['Latest Data'])

我可以在网上找到的所有文档都指出,从数据集中提取特定列需要您在方括号中指定列标题的名称,但是当我尝试这样做时,这会返回 TypeError:

>
    print (df['Latest Data'])
TypeError: list indices must be integers or slices, not str

如果您对数据集的外观感到好奇而不尝试指定列:

     SpotGamma Proprietary Levels Latest Data  ...    NDX    QQQ
0                        Ref Price:        4465  ...  15283    372
1        SpotGamma Imp. 1 Day Move:      0.91%,  ...    NaN    NaN
2        SpotGamma Imp. 5 Day Move:       2.11%  ...    NaN    NaN
3           SpotGamma Gamma Index™:        0.48  ...   0.04  -0.08
4              Volatility Trigger™:        4415  ...  15075    373
5  SpotGamma Absolute Gamma Strike:        4450  ...  15500    370
6               Gamma Notional(MM):        $157  ...     $4  $-397

【问题讨论】:

    标签: python pandas beautifulsoup


    【解决方案1】:

    注意

    df = pd.read_html(os.path.expanduser("~/Documents/HTMLSpider/HTMLSpider_test/spotgamma.html"))
    

    将返回一个列表数据框,而不是一个。

    参见:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_html.html(“将 HTML 表格读入 DataFrame 对象列表。”)

    最好做

    ldf = pd.read_html(os.path.expanduser("~/Documents/HTMLSpider/HTMLSpider_test/spotgamma.html"))
    

    然后

    df = ldf[0]  # replace 0 with the number of the dataframe you want
    

    要获取第一个数据框(可能还有更多,请查看 len(ldf) 以查看您获得了多少以及哪个具有您需要的列)。

    【讨论】:

    • 如果是这样,(因为你是新人)请将此标记为“已解决”
    • 在我能够将其标记为已解决之前有一个冷却时间,我只是在等待它用完。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-02
    • 2016-07-01
    • 2020-08-19
    • 1970-01-01
    • 2013-01-06
    • 1970-01-01
    相关资源
    最近更新 更多