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

Kaggle学习中sns.countplot报KeyError:0错误求助

问题:Seaborn countplot 出现 KeyError: 0 错误

我是Kaggle新手,正在学习《spaceship titanic》指南内容,已经解决了新版本Python下Eli5的导入兼容问题。执行以下代码时出现KeyError:0错误:

# Joint distribution of Group and HomePlanet
GHP_gb=data.groupby(['Group','HomePlanet'])['HomePlanet'].size().unstack().fillna(0)
GHP_gb.head()

# Countplot of unique values
sns.countplot((GHP_gb>0).sum(axis=1))
plt.title('Number of unique home planets per group')

报错信息如下:

KeyError                                  Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   3801             try:
-> 3802                 return self._engine.get_loc(casted_key)
   3803             except KeyError as err:

8 frames
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

KeyError: 0

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   3802                 return self._engine.get_loc(casted_key)
   3803             except KeyError as err:
-> 3804                 raise KeyError(key) from err
   3805             except TypeError:
   3806                 # If we have a listlike key, _check_indexing_error will raise

KeyError: 0

尝试修改axis值为0,或改为sns.countplot(GHP_gb>0).sum(axis=1),虽仍有错误但能看到数据。请问该代码问题出在哪里,如何解决?


错误原因

sns.countplot()的参数使用逻辑有误:

  • 你直接传入了一个Pandas Series((GHP_gb>0).sum(axis=1)的计算结果),但新版Seaborn的countplot默认会把传入的对象当成DataFrame,尝试按列名取数据——这里误将Series的索引当作列名查找,自然找不到名为0的列,抛出KeyError。
  • 你尝试的sns.countplot(GHP_gb>0).sum(axis=1)是语法错误,countplot返回的是绘图的Axes对象,不能直接调用.sum()方法。

解决方法

有两种简单的修正方式:

  1. 明确指定x参数为计算后的Series:
# Countplot of unique values
sns.countplot(x=(GHP_gb>0).sum(axis=1))
plt.title('Number of unique home planets per group')
  1. 将计算结果转为带列名的DataFrame,再传入countplot:
import pandas as pd

# 先将结果转为带列名的DataFrame
count_df = pd.DataFrame({'unique_planets': (GHP_gb>0).sum(axis=1)})
sns.countplot(data=count_df, x='unique_planets')
plt.title('Number of unique home planets per group')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 12:56:01