如何修复:TypeError: no numeric data to plot
在这篇文章中,我们将修复这个错误。TypeError: no numeric data to plot.
这种错误发生的情况:
# importing pandas
import pandas as pd
# importing numpy
import numpy as np
import matplotlib.pyplot as plt
petal_length = ['3.3', '3.5', '4.0', '4.5',
'4.6', '5.0', '5.5', '6.0',
'6.5', '7.0']
petal_width = ['3.6', '3.8', '4.4', '6.6',
'6.8', '7.0', '7.5', '8.0',
'8.5', '8.9']
df = pd.DataFrame({'petal_length(cm)': petal_length,
'petal_width(cm)': petal_width})
df.plot(x='petal_length(cm)', y='petal_width(cm)')
plt.show()
输出:
TypeError: no numeric data to plot
错误原因:
绘图只能在数字数据上进行,当我们绘制的数据类型不同于数字数据时,就会出现这个错误。要知道数据类型是否为数字,我们可以通过使用函数dtypes()来知道。
print(df.dtypes)
我们用来绘制的数据必须是数字的。
修复错误
这个错误可以通过将要绘制的数据转换为数字数据来解决。为了将数据转换为数字数据,我们可以使用函数 astype() 或 to_numeric()。
方法1:使用 astype() 函数
语法:
df['column_name']= df['column_name'].astype(data_type)
其中,df是输入数据帧
示例:
# importing pandas
import pandas as pd
# importing numpy
import numpy as np
# importing matplotlib.pyplot
import matplotlib.pyplot as plt
petal_length = ['3.3', '3.5', '4.0', '4.5',
'4.6', '5.0', '5.5', '6.0',
'6.5', '7.0']
petal_width = ['3.6', '3.8', '4.4', '6.6',
'6.8', '7.0', '7.5', '8.0',
'8.5', '8.9']
df = pd.DataFrame({'petal_length(cm)': petal_length,
'petal_width(cm)': petal_width})
df['petal_length(cm)'] = df['petal_length(cm)'].astype(float)
df['petal_width(cm)'] = df['petal_width(cm)'].astype(float)
df.plot(x='petal_length(cm)', y='petal_width(cm)')
plt.show()
输出 :
方法2 :使用to_numeric()函数
语法:
df['column_name'] = pd.to_numeric(df['column_name'])
其中df是输入数据帧
示例 :
# importing pandas
import pandas as pd
# importing numpy
import numpy as np
# importing matplotlib.pyplot
import matplotlib.pyplot as plt
petal_length = ['3.3', '3.5', '4.0', '4.5',
'4.6', '5.0', '5.5', '6.0',
'6.5', '7.0']
petal_width = ['3.6', '3.8', '4.4', '6.6',
'6.8', '7.0', '7.5', '8.0',
'8.5', '8.9']
df = pd.DataFrame({'petal_length(cm)': petal_length,
'petal_width(cm)': petal_width})
# Using to_numeric() function
df['petal_length(cm)'] = pd.to_numeric(df['petal_length(cm)'])
df['petal_width(cm)'] = pd.to_numeric(df['petal_width(cm)'])
df.plot(x='petal_length(cm)', y='petal_width(cm)')
plt.show()
输出: