使用python-pandas索引数据帧时无法获得非唯一标签的正确切片边界 [英] Cannot get right slice bound for non-unique label when indexing data frame with python-pandas

查看:930
本文介绍了使用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!

推荐答案

说明了错误消息 .loc.iloc之间的区别是基于label与基于integer position的索引-

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索引数据帧时无法获得非唯一标签的正确切片边界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆