python-3.x - 将“空数据框”/列表项转换为数据框?
问题描述
我使用 Selenium(通过 xpath)从网站解析了一个表格,然后pd.read_html
在表格元素上使用,现在我留下了一个看起来像组成表格的列表。它看起来像这样:
[Empty DataFrame
Columns: [Symbol, Expiration, Strike, Last, Open, High, Low, Change, Volume]
Index: [], Symbol Expiration Strike Last Open High Low Change Volume
0 XPEV Dec20 12/18/2020 46.5 3.40 3.00 5.05 2.49 1.08 696.0
1 XPEV Dec20 12/18/2020 47.0 3.15 3.10 4.80 2.00 1.02 2359.0
2 XPEV Dec20 12/18/2020 47.5 2.80 2.67 4.50 1.89 0.91 2231.0
3 XPEV Dec20 12/18/2020 48.0 2.51 2.50 4.29 1.66 0.85 3887.0
4 XPEV Dec20 12/18/2020 48.5 2.22 2.34 3.80 1.51 0.72 2862.0
5 XPEV Dec20 12/18/2020 49.0 1.84 2.00 3.55 1.34 0.49 4382.0
6 XPEV Dec20 12/18/2020 50.0 1.36 1.76 3.10 1.02 0.30 14578.0
7 XPEV Dec20 12/18/2020 51.0 1.14 1.26 2.62 0.78 0.31 4429.0
8 XPEV Dec20 12/18/2020 52.0 0.85 0.95 2.20 0.62 0.19 2775.0
9 XPEV Dec20 12/18/2020 53.0 0.63 0.79 1.85 0.50 0.13 1542.0]
如何将其转换为实际的数据框,以“符号、过期等...”作为标题,将最左侧的列作为索引?
我一直在尝试几种不同的方法,但无济于事。我离开的地方是尝试:
# From reading the html of the table step
dfs = pd.read_html(table.get_attribute('outerHTML'))
dfs = pd.DataFrame(dfs)
...当我打印新的 dfs 时,我得到了这个:
0 Empty DataFrame
Columns: [Symbol, Expiration, ...
1 Symbol Expiration Strike Last Open ...
解决方案
根据pandas.read_html
文档,
此函数将始终返回一个列表,
DataFrame
否则它将失败,例如,它不会返回一个空列表。
根据您的列表输出,非空数据框是该列表中的第二个元素。所以通过索引来检索它(记住 Python 使用零作为可迭代的第一个索引)。请注意,您可以使用存储在列表或字典中的数据框。
dfs[1].head()
dfs[1].tail()
dfs[1].describe()
...
single_df = dfs[1].copy()
del dfs
或在同一个调用中索引
single_df = pd.read_html(...)[1]
推荐阅读
- swift - 包解析失败。无法获取标签列表
- vba - 无法附加工作簿以通过 vba 按钮发送
- angular - 对象的等价物...来自角度的java
- spring-integration - 是否可以关闭 SFTP 会话工厂设置的文件的锁定
- python - “复制” Python 和“不完整”导入?
- flutter - 您如何强制将颤振应用程序上的所有字符串本地化?
- python - 如何使用 If 条件修改数据框中的变量?
- spring-boot - 如何在 Spring Boot 应用程序中生成日志文件
- reactjs - React Redux 条件渲染错误?
- python - 为什么用 Python urllib.request 下载 json 这么慢?我怎样才能让它更快?