Pandas 是否可以在分层索引中使用loc[]的整数索引?

Pandas 是否可以在分层索引中使用loc[]的整数索引?,pandas,Pandas,我认为.loc[]只允许标签索引或布尔索引,但在这段代码中,整数索引在层次索引系列(data.loc[:,2])中的.loc[]中使用。这是否仅在层次索引系列/数据帧中可能,还是因为整数索引在构造函数中指定 data = pd.Series(np.random.randn(9), index=[['a', 'a', 'a', 'b', 'b', 'c', 'c', 'd', 'd'], [1,2,3,1,3,1,2,2,3]]) a 1 -0.204708 2

我认为.loc[]只允许标签索引或布尔索引,但在这段代码中,整数索引在层次索引系列(data.loc[:,2])中的.loc[]中使用。这是否仅在层次索引系列/数据帧中可能,还是因为整数索引在构造函数中指定

data = pd.Series(np.random.randn(9), index=[['a', 'a', 'a', 'b', 'b', 'c', 'c', 'd', 'd'], [1,2,3,1,3,1,2,2,3]])

    a  1   -0.204708
       2    0.478943
       3   -0.519439
    b  1   -0.555730
       3    1.965781
    c  1    1.393406
       2    0.092908
    d  2    0.281746
       3    0.769023

data.loc[:, 2]

    a    0.478943
    c    0.092908
    d    0.281746
    dtype: float64

引用文件:

Series.loc
Access a group of rows and columns by label(s) or a boolean array.

.loc[] is primarily label based, but may also be used with a boolean array.

Allowed inputs are:

A single label, e.g. 5 or 'a', (note that 5 is interpreted as a label of the index, and never as an integer position along the index).
在您的示例中,2被解释为索引标签,而不是位置。 对于非分层索引系列,也可以执行相同的操作:

data = pd.Series(np.random.randn(9))
data.loc[2]