首页 > 解决方案 > 可以在分层索引中使用 loc[] 的整数索引吗?

问题描述

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

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

标签: pandas

解决方案


从文档中引用:

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]

推荐阅读