熊猫索引和关键错误

时间:2018-07-20 15:14:45

标签: python pandas indexing

请考虑以下内容:

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]应该会出现密钥错误。我不知道我在想什么。有人可以澄清在哪种情况下我会收到密钥错误吗?

3 个答案:

答案 0 :(得分:3)

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

当请求df.B[0]时,熊猫的行为是模棱两可的,取决于索引的数据类型和传递给python slice语法的value的数据类型。它的行为可能类似于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

答案 1 :(得分:0)

df.B返回一个熊猫系列,这就是为什么您可以进行位置索引的原因。如果选择B列作为数据框,则会引发错误:

df[['B']][0]

答案 2 :(得分:0)

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

data structure documentation

中的更多信息
  

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