首页 > 解决方案 > Python:使用 pandas 读取 HTML 表格并使用 matplotlib 绘图

问题描述

所以我已经阅读了一个 HTML 表格,read_html并将其存储在一个 DataFrame 中。但是当我尝试绘制它回复的 DF 时Empty 'DataFrame' : no numeric data to plot,我尝试将数据类型从字符串转换为浮点数或整数,但出现“无法转换为浮点数”的错误。

import pandas as pd
import datetime
import matplotlib.pyplot as plt
from matplotlib import style
style.use('ggplot')

# read data and create a df, it will take all page tables
df = pd.read_html('https://money.cnn.com/data/us_markets/')

# Take the first read table only
df = df[0]

# Set the first column as the index
df.set_index(0, inplace=True)

df.plot()
plt.show()

错误

标签: pythonpandasmatplotlib

解决方案


尝试:

df = pd.read_html('https://money.cnn.com/data/us_markets')
df = df[0]

df.set_index(df.columns[0]).plot(figsize=(15,8))

这行得通。

在此处输入图像描述


推荐阅读