与列表不同,pandas中的负索引给出KeyError

问题描述 投票:4回答:1

使用Python列表,您可以使用负索引进行切片

a = [1,2,3,4,5,6,7,8,9]
print a[-1] 

将按预期打印9。

然而,

a=pd.Series([1,2,3,4,5,6,7,8,9])
print a[-1] 

给出KeyError:-1L

pandas indexing slice series keyerror
1个回答
2
投票

使用iloc来获取位置而不是标签:

In [11]: a.iloc[-1]
Out[11]: 9

selection section of the docs

© www.soinside.com 2019 - 2024. All rights reserved.