本文介绍了使用python-pandas索引数据帧时无法获得非唯一标签的正确切片边界的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的数据框df:

a         b
10        2
3         1
0         0
0         4
....
# about 50,000+ rows

我希望选择df[:5, 'a'].但是当我呼叫df.loc[:5, 'a']时,出现错误:KeyError: 'Cannot get right slice bound for non-unique label: 5.当我调用df.loc[5]时,结果包含250行,而当我使用df.iloc[5]时只有一行.为什么会发生这种情况,如何正确索引呢?先感谢您!

I wish to choose the df[:5, 'a']. But When I call df.loc[:5, 'a'], I got an error: KeyError: 'Cannot get right slice bound for non-unique label: 5. When I call df.loc[5], the result contains 250 rows while there is just one when I use df.iloc[5]. Why does this thing happen and how can I index it properly? Thank you in advance!

推荐答案

说明了错误消息此处:if the index is not monotonic, then both slice bounds must be unique members of the index.

.loc.iloc之间的区别是基于label与基于integer position的索引-请参阅文档. .loc用于选择单独的labelsslices标签.这就是.loc[5]选择index的值为250的所有行的原因(错误是关于非唯一索引的).相反,iloc选择第5行(0索引).这就是为什么只得到一行的原因,索引值可能是5,也可能不是.希望这会有所帮助!

The difference between .loc and .iloc is label vs integer position based indexing - see docs. .loc is intended to select individual labels or slices of labels. That's why .loc[5] selects all rows where the index has the value 250 (and the error is about a non-unique index). iloc, in contrast, select row number 5 (0-indexed). That's why you only get a single row, and the index value may or may not be 5. Hope this helps!

这篇关于使用python-pandas索引数据帧时无法获得非唯一标签的正确切片边界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 15:02