pandas 切片不包括末尾 [英] Pandas slicing excluding the end

查看:117
本文介绍了 pandas 切片不包括末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用loc切片数据框时,

When slicing a dataframe using loc,

df.loc [开始:结束]

df.loc[start:end]

包括开始和结束.使用loc时,有没有一种简单的方法可以排除结尾?

both start and end are included. Is there an easy way to exclude the end when using loc?

推荐答案

loc 包括开始和结束,一种较不理想的解决方法是获取索引位置并使用iloc切片数据帧(假设您没有重复的索引) ):

loc includes both the start and end, one less ideal work around is to get the index position and use iloc to slice the data frame (assume you don't have duplicated index):

df=pd.DataFrame({'A':[1,2,3,4]}, index = ['a','b','c','d'])

df.iloc[df.index.get_loc('a'):df.index.get_loc('c')]

#   A
#a  1
#b  2

df.loc['a':'c']

#   A
#a  1
#b  2
#c  3

这篇关于 pandas 切片不包括末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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