为什么大熊猫中的.loc切片包含stop,这与典型的python切片相反?

jto*_*rca 2 python pandas

我正在切片pandas数据框,并且.loc与numpy和普通python切片相比,我似乎正在使用来获得意外切片。请参见下面的示例。

>>> import pandas as pd
>>> a = pd.DataFrame([[0,1,2],[3,4,5],[4,5,6],[9,10,11],[34,2,1]])
>>> a
    0   1   2
0   0   1   2
1   3   4   5
2   4   5   6
3   9  10  11
4  34   2   1
>>> a.loc[1:3, :]
   0   1   2
1  3   4   5
2  4   5   6
3  9  10  11
>>> a.values[1:3, :]
array([[3, 4, 5],
       [4, 5, 6]])
Run Code Online (Sandbox Code Playgroud)

有趣的是,这仅发生于.loc,而不是.iloc

>>> a.iloc[1:3, :]
   0  1  2
1  3  4  5
2  4  5  6
Run Code Online (Sandbox Code Playgroud)

因此,.loc似乎包含终止索引,但numpy .iloc却不包含。

通过评论,看来这不是一个错误,我们受到了警告。但是为什么会这样呢?

ALo*_*llz 6

请记住.loc主要是基于标签的索引。使用non-RangeIndex时,包含stop端点的决定变得更加明显:

df = pd.DataFrame([1,2,3,4], index=list('achz'))
#   0
#a  1
#c  2
#h  3
#z  4
Run Code Online (Sandbox Code Playgroud)

如果我想选择'a'和之间'h'(包括在内)的所有行,我只会知道'a''h'。为了与其他python切片保持一致,您还需要知道遵循的索引'h',在这种情况下该索引是'z' 但可能是任何东西。


隐藏了文档的一部分,解释了此设计选择。端点是包容的