Python Key Error=0 从 err 引发 KeyError(key)

Python Key Error=0 raise KeyError(key) from err

提问人:Bon 提问时间:11/15/2023 最后编辑:Bon 更新时间:11/17/2023 访问量:56

问:

首先,感谢您抽出宝贵时间查看此问题。

我是 kaggle 的新手。泰坦尼克号宇宙飞船我目前正在研究上面链接中的指南。

修复了较新 Python 的 Eli5 导入问题。(不再兼容)。

# 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')

到目前为止,我已经取得了良好的进展,但是 In[24] 中的代码抛出了一个我无法弄清楚的错误,如下所示。

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

将轴值更改为 0 或

sns.countplot(GHP_gb>0).sum(axis=1)

如果进行上述更改,则会看到一些错误,但仍能看到数据。

代码中似乎没有错误,那么我怎么知道出了什么问题呢?

谢谢。

python pandas 键错误 kaggle

评论


答:

0赞 Zihao 11/17/2023 #1

我尝试了 kaggle 笔记本,但无法重现错误。 如果已经使用了本地环境,则可能与 python 依赖的版本有关。

评论

0赞 Bon 11/17/2023
谢谢你的评论。我正在使用谷歌colab。