You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib绘制柱状图时X轴显示NaN问题求助——基于Pandas处理英超帽子戏法射手数据

解决Pandas绘图时X轴显示NaN的问题

我来帮你拆解一下问题根源,然后给出几个可行的解决方案:

问题原因

你执行groupby(['Player'])之后,Player字段已经变成了DataFrame的索引,不再是普通的列。所以你的top10DataFrame里其实只有Goals这一列,没有名为Player的列。当你尝试用pd.DataFrame(top10,columns=['Player','Goals'])新建DataFrame时,因为找不到Player列,这一列就会被填充为NaN,绘图时自然X轴全是nan了。

解决方案

这里有三种简单的修复方式,选哪种都可以:

方法1:GroupBy时保留Player为列

在groupby的时候加上as_index=False参数,让Player保持为普通列,这样后续直接绘图就不会有问题:

import matplotlib.pyplot as plt
import pandas as pd

# 修改groupby语句,添加as_index=False
top10 = df.groupby(['Player'], as_index=False)[['Goals']].count().sort_values(['Goals'], ascending=False).head(10)
# 直接绘图
top10.plot(x='Player', y='Goals', kind='bar')
plt.show()

方法2:将索引转换为列

如果你已经生成了top10,可以用reset_index()把Player索引转成普通列:

# 把索引转成列
top10 = top10.reset_index()
# 现在Player是列了,可以正常绘图
top10.plot(x='Player', y='Goals', kind='bar')
plt.show()

方法3:直接用索引作为X轴

既然Player已经是索引,绘图时可以不用指定x参数,默认会用索引作为X轴,之后再手动设置X轴标签即可:

top10.plot(kind='bar')
# 设置轴标签
plt.xlabel('Player')
plt.ylabel('Number of Hat-Tricks')
plt.show()

这三种方法都能解决你X轴显示nan的问题,选最适合你当前代码流程的就行~

内容的提问来源于stack exchange,提问作者Neil White

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.01 03:02:29