如何在Pandas中修复:TypeError没有数字数据可供绘制

630 阅读2分钟

在使用pandas时,你可能遇到的一个错误是:

TypeError: no numeric data to plot

当你试图绘制pandas DataFrame中的数值,但没有数字值可供绘制时,就会出现这个错误。

这个错误通常发生在你认为DataFrame中的某一列是数字的,但结果却是不同的数据类型。

下面的例子显示了如何在实践中解决这个错误。

如何重现这个错误

假设我们有下面这个pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team': ['A', 'A', 'B', 'B', 'B'],
                   'points': ['5', '7', '7', '9', '12'],
                   'rebounds': ['11', '8', '10', '6', '6'],
                   'blocks': ['4', '7', '7', '6', '5']})

#view DataFrame
df

	team	points	rebounds blocks
0	A	5	11	 4
1	A	7	8	 7
2	B	7	10	 7
3	B	9	6	 6
4	B	12	6	 5

现在假设我们试图为我们认为是数字的三个变量创建一个线图:点数、篮板和盖帽:

#attempt to create line plot for points, rebounds, and blocks
df[['points', 'rebounds', 'blocks']].plot()

ValueError: no numeric data to plot

我们收到了一个错误,因为这些列实际上都不是数字的。

如何修复这个错误

我们可以使用dtypes函数来查看我们的DataFrame中每一列是什么数据类型:

#display data type of each column in DataFrame
df.dtypes

team        object
points      object
rebounds    object
blocks      object
dtype: object

我们可以看到,DataFrame中没有一列是数字。

我们可以使用.astype()函数将特定的列转换为数字型。

#convert points, rebounds, and blocks columns to numeric
df['points']=df['points'].astype(float)
df['rebounds']=df['rebounds'].astype(float)
df['blocks']=df['blocks'].astype(float)

然后我们可以再次使用plot()函数:

#create line plot for points, rebounds, and blocks
df[['points', 'rebounds', 'blocks']].plot()

我们能够成功地为点、篮板和块创建一个线图,因为现在每个变量都是数字的。

我们可以通过再次使用dtypes函数来验证这一点:

#display data type of each column in DataFrame
df.dtypes

team         object
points      float64
rebounds    float64
blocks      float64
dtype: object

其他资源

下面的教程解释了如何修复Python中的其他常见错误:

如何修复Pandas中的KeyError
如何修复ValueError:无法将浮点数NaN转换为整数
如何修复ValueError:操作数不能与形状一起广播