How to Fix in Pandas: TypeError: no numeric data to plot


One error you may encounter when using pandas is:

TypeError: no numeric data to plot

This error occurs when you attempt to plot values from a pandas DataFrame, but there are no numeric values to plot.

This error typically occurs when you think a certain column in the DataFrame is numeric but it turns out to be a different data type.

The following example shows how to fix this error in practice.

How to Reproduce the Error

Suppose we have the following 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

Now suppose we attempt to create a line plot for the three variables that we believe are numeric: points, rebounds, and blocks:

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

ValueError: no numeric data to plot

We receive an error because none of these columns are actually numeric.

How to Fix the Error

We can use the dtypes function to see what data type each column is in our DataFrame:

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

team        object
points      object
rebounds    object
blocks      object
dtype: object

We can see that none of the columns in the DataFrame are numeric.

We can use the .astype() function to convert specific columns to numeric:

#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)

We can then use the plot() function again:

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

We’re able to successfully create a line plot for points, rebounds, and blocks because each variable is now numeric.

We can verify this by using the dtypes function once again:

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

team         object
points      float64
rebounds    float64
blocks      float64
dtype: object

Additional Resources

The following tutorials explain how to fix other common errors in Python:

How to Fix KeyError in Pandas
How to Fix: ValueError: cannot convert float NaN to integer
How to Fix: ValueError: operands could not be broadcast together with shapes

Leave a Reply

Your email address will not be published.