pandas 熊猫切片不包括结尾
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45523749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas slicing excluding the end
提问by zcadqe
When slicing a dataframe using loc,
使用 loc 对数据帧进行切片时,
df.loc[start:end]
df.loc[开始:结束]
both start and end are included. Is there an easy way to exclude the end when using loc?
包括开始和结束。使用 loc 时是否有一种简单的方法可以排除结尾?
回答by Psidom
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):
loc
包括开始和结束,一个不太理想的解决方法是获取索引位置并用于iloc
对数据框进行切片(假设您没有重复的索引):
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
回答by WillZ
Easiest I can think of is df.loc[start:end].iloc[:-1]
.
我能想到的最简单的就是df.loc[start:end].iloc[:-1]
.
Chops off the last one.
砍掉最后一个。