熊猫索引和关键错误

新手上路,请多包涵

考虑以下:

 d = {'a': 0.0, 'b': 1.0, 'c': 2.0}

e = pd.Series(d, index = ['a', 'b', 'c'])

df = pd.DataFrame({ 'A' : 1.,'B' : e,'C' :pd.Timestamp('20130102')}).

当我尝试通过以下方式访问 B 列的第一行时:

 >>> df.B[0]
0.0

我得到正确的结果。

但是,在阅读 KeyError: 0 when accessing value in pandas series 之后,我假设,因为我已将索引指定为“a”、“b”和“c”,所以正确的方法是访问列的第一行B(使用位置参数)是: df.B.iloc[0]df.B[0] 应该引发关键错误。我不知道我错过了什么。有人可以澄清在哪种情况下我会收到 Key Error 吗?

原文由 Yash 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 656
2 个回答

您引用的问题中的问题是给定数据帧的索引是整数,但不是从 0 开始。

Pandas 在请求 df.B[0] 时的行为是不明确的,取决于索引的数据类型和传递给 python slice 语法的值的数据类型。它的行为可能类似于 df.B.loc[0] (基于索引标签)或 df.B.iloc[0] (基于位置)或其他我不知道的东西。对于可预测的行为,我建议使用 lociloc

用你的例子来说明这一点:

 d = [0.0, 1.0, 2.0]
e = pd.Series(d, index = ['a', 'b', 'c'])
df = pd.DataFrame({'A': 1., 'B': e, 'C': pd.Timestamp('20130102')})

df.B[0] # 0.0 - fall back to position based
df.B['0'] # KeyError - no label '0' in index
df.B['a'] # 0.0 - found label 'a' in index
df.B.loc[0] # TypeError - string index queried by integer value
df.B.loc['0'] # KeyError - no label '0' in index
df.B.loc['a'] # 0.0 - found label 'a' in index
df.B.iloc[0] # 0.0 - position based query for row 0
df.B.iloc['0'] # TypeError - string can't be used for position
df.B.iloc['a'] # TypeError - string can't be used for position

以参考文章中的示例为例:

 d = [0.0, 1.0, 2.0]
e = pd.Series(d, index = [4, 5, 6])
df = pd.DataFrame({'A': 1., 'B': e, 'C': pd.Timestamp('20130102')})

df.B[0] # KeyError - label 0 not in index
df.B['0'] # KeyError - label '0' not in index
df.B.loc[0] # KeyError - label 0 not in index
df.B.loc['0'] # KeyError - label '0' not in index
df.B.iloc[0] # 0.0 - position based query for row 0
df.B.iloc['0'] # TypeError - string can't be used for position

原文由 Justinas Marozas 发布,翻译遵循 CC BY-SA 4.0 许可协议

df.B 实际上是一个 pandas.Series 对象( df['B'] 的快捷方式),可以迭代。 df.B[0] 不再是“行”,而只是 df.B 的第一个元素,因为通过编写 df.B 你基本上创建了一个一维对象

数据结构文档 中的更多信息

您可以在语义上将 DataFrame 视为类似索引的 Series 对象的字典。

原文由 NiGiord 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题