python - Pandas 索引和 key 错误

标签 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] 应该引发 key 错误。我不知道我错过了什么。有人可以澄清在哪种情况下我会收到 Key Error 吗?

最佳答案

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

Pandas 在请求 df.B[0] 时的行为不明确,取决于索引的数据类型和传递给 python 切片语法的值的数据类型。它可以表现得像 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

关于python - Pandas 索引和 key 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51445631/

相关文章:

python - 从 Pandas 数据框的两列创建矩形热图

python - 如何将 unicode 转换为 unicode 转义文本

python - 从行值创建列并填充 - pandas

algorithm - 关于空间索引的好书/文章

mysql - 为什么mysql更喜欢扫描表而不是使用复合索引?

python - 任务队列 : Allow only one task at a time per user

python - Pandas:根据行内容定位和更新值

python - Pandas groupby 和多列的加权和

sql - 具有许多不使用部分索引的值的 Postgres IN 子句

python - numpy/pandas 矩阵乘法的多线程?