temp = pd.Series(np.random.randint(1, 10, 5), index=['John', 'Joe', 'Bob', 'Alice', 'Kris'])
temp[-1]
此输出为与“Kris”关联的值 然而,当我这样做时:
temp2 = pd.Series(['John', 'Joe', 'Bob', 'Alice', 'Kris'], index=[5, 6, 7, 8, 9])
temp2[-1]
它抛出一个KeyError
我有一个简单的想法,当自定义索引为非整数类型时,Pandas 在内部执行索引,但我在这里不明白的是,负索引是如何工作的? -1 本质上意味着 Pandas 引用自定义索引列表,然后获取第“-1”或最后一个元素,即 Kris,然后将“Kris”作为标签传递给索引?
我确实知道单个整数在索引中被视为标签,那么这是如何工作的呢?这也仅适用于类型为非整数的自定义索引;我在这里缺少什么?