python - 如何处理空 'DataFrame' : no numeric data to plot error to take string on the graphs

标签 python pandas dataframe matplotlib data-science

enter image description here我正在为我的项目做类似下面的事情;

df =pd.DataFrame ({City: ['London', ‘Jakarta’, 'Newyork', 'Mumbai'],
‘Staff’: ['1000','2000','3000','4000']})
print (df.head())
df.plot(kind='line',x=’City’,y=’Staff’,color='red')
plt.show()

对于此代码,我收到错误如下 类型错误:空“DataFrame”:没有要绘制的数字数据。

然后我添加以下代码片段:

df.Staff=pd.to_numeric(df.Staff)

但出现同样的错误。 有没有办法在图表上取字符串? 或者我需要重新定义为;

x = ['London', ‘Jakarta’, 'Newyork', 'Mumbai']
y = ['1000','2000','3000','4000']

我检查了以前的解决方案,但看起来没有什么东西

最佳答案

您的错误是由于您输入的数据格式不正确造成的。请参阅下面的示例(请注意 Staff 列,是数字,而不是您输入的字符串):

df =pd.DataFrame ({'City': ['London', 'Jakarta', 'Newyork', 'Mumbai'],
                   'Staff': [1000,2000,3000,4000]})
df.plot(kind='line',x='City', y='Staff', color= 'red')

enter image description here

如果您仍想以字符串形式输入数字数据,以下内容将为您提供帮助:

df =pd.DataFrame ({'City': ['London', 'Jakarta', 'Newyork', 'Mumbai'],
                   'Staff': ['1000','2000','3000','4000']})

df['Staff'] = df['Staff'].astype("int") # astype("float")
df.plot(kind='line',x='City', y='Staff', color= 'red')

甚至:

df =pd.DataFrame ({'City': ['London', 'Jakarta', 'Newyork', 'Mumbai'],
                   'Staff': ['1000','2000','3000','4000']})

df['Staff'] = pd.to_numeric(df['Staff'])
df.plot(kind='line',x='City', y='Staff', color= 'red')

关于python - 如何处理空 'DataFrame' : no numeric data to plot error to take string on the graphs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60297951/

相关文章:

python - 如何将 pandas 数据框列转换为 native python 数据类型?

dictionary - 从数据框字典中提取数据框

r - 重命名R中的一个命名列

python - 按 Pandas 列总和的值分组

与 R data.frame 类似的 Java 对象

python - 从源表中获取未合并的数据

Python输入错误

python - 在 pyinstaller 可执行程序中找不到 Streamlit 发行版

python - 组合Python 3格式(尝试同时使用千位分隔符和两位小数)

python - pyautogui可以用来防止windows锁屏吗?