Fix the Pandas: TypeError: no numeric data to plot
In this tutorial, we will learn what is ‘TypeError: no numeric data to plot‘ and how to fix it. For this, we need to understand how plots in Pandas work. Only numerical data type values can be plotted in Pandas. Python will raise the error ‘no numeric data to plot’ if we try anything other than a numerical data type.
Occurrence of this error
Example:
import pandas as pd import matplotlib.pyplot as plt data = pd.DataFrame({'Teams': ['A', 'B', 'C', 'D'], 'Scores': ['40', '38', '30', '45'], 'GPA': ['8.5', '7.4', '6.2', '7.6']}) print(data) data[['Scores', 'GPA']].plot() plt.show()
Output:
TypeError: no numeric data to plot
- This is happening because the data type of the columns may not be numerical. Let’s check it with
dtypes()
function.
print(data.dtypes)
Output:
Teams object Scores object GPA object dtype: object
Fixing the error: TypeError: no numeric data to plot
We can fix this error using two methods. They are,
- Using astype()
- Using to_numeric()
Using astype()
Syntax:
data['column_name']=data['column_name'].astype(datatype)
Let us fix the error by converting pandas object data type into numeric using this function,
import pandas as pd import matplotlib.pyplot as plt data = pd.DataFrame({'Teams': ['A', 'B', 'C', 'D'], 'Scores': ['40', '38', '30', '45'], 'GPA': ['8.5', '7.4', '6.2', '7.6']}) data['Scores']=data['Scores'].astype(float) data['GPA']=data['GPA'].astype(float) data[['Scores','GPA']].plot() plt.show()
Output:
- This is successful because we changed the data type of the columns into numeric. Let’s check it,
print(data.dtypes)
Output:
Teams object Scores float64 GPA float64 dtype: object
Using to_numeric()
Syntax:
data['column_name']=pd.to_numeric(data['column_name'])
This is another method used to change data type into numeric. Let us try to solve this issue using this method,
import pandas as pd import matplotlib.pyplot as plt data = pd.DataFrame({'Teams': ['A', 'B', 'C', 'D'], 'Scores': ['40', '38', '30', '45'], 'GPA': ['8.5', '7.4', '6.2', '7.6']}) data['Scores']=pd.to_numeric(data['Scores']) data['GPA']=pd.to_numeric(data['GPA']) data[['Scores','GPA']].plot() plt.show()
Output:
- This is successful because we changed the data type of the columns into numeric (int or float). Let’s check it,
print(data.dtypes)
Output:
Teams object Scores int64 GPA float64 dtype: object
Leave a Reply