【问题标题】:Setting values of multiindex dataframe using only one-level indexing仅使用一级索引设置多索引数据帧的值
【发布时间】:2026-01-30 13:50:01
【问题描述】:

我的问题是这个话题的合乎逻辑的延续: Setting values with multiindex in pandas。所以这个例子和答案也适合我的情况。

他们用f.loc[(slice(None), "one"), 0] = 1设置了一个多索引值

但就我而言,我有很多具有自定义索引级别数的数据框,所以我想只在最后一级使用索引,而不指定其他 -喜欢f.loc[:::, "one"), 0] = 1。 附:另外,如果我有一个“一”列的Indexer,我可以使用它吗? 索引器可以是一个数组:array([ True, True, True, ..., True, True, True], dtype=bool)

【问题讨论】:

    标签: python pandas indexing


    【解决方案1】:

    你要使用的IIUCpd.IndexSlice

    In [276]: df
    Out[276]:
                         0         1
    first second
    bar   one     0.414213 -0.316333
          two     1.109279  0.307283
    baz   one    -0.287986 -1.963492
          two     0.858867  0.553895
    foo   one    -0.152813 -2.489409
          two     1.022960  0.377656
    qux   one     1.549389 -0.307250
          two    -1.150914 -3.517356
    
    In [277]: df.loc[pd.IndexSlice[:,'one'], 0] = 1
    
    In [278]: df
    Out[278]:
                         0         1
    first second
    bar   one     1.000000 -0.316333
          two     1.109279  0.307283
    baz   one     1.000000 -1.963492
          two     0.858867  0.553895
    foo   one     1.000000 -2.489409
          two     1.022960  0.377656
    qux   one     1.000000 -0.307250
          two    -1.150914 -3.517356
    

    使用mask的布尔索引:

    In [291]: mask = (df[0] > 1).values
    
    In [292]: mask
    Out[292]: array([False,  True, False, False, False,  True, False, False], dtype=bool)
    
    In [293]: df.loc[mask]
    Out[293]:
                         0         1
    first second
    bar   two     1.109279  0.307283
    foo   two     1.022960  0.377656
    
    In [294]: df.iloc[mask]
    Out[294]:
                         0         1
    first second
    bar   two     1.109279  0.307283
    foo   two     1.022960  0.377656
    
    In [295]: df[mask]
    Out[295]:
                         0         1
    first second
    bar   two     1.109279  0.307283
    foo   two     1.022960  0.377656
    

    【讨论】:

    • 谢谢。您能否添加P.S.的信息
    • @LadenkovVladislav,对不起,我不明白部分。你的Indexer 是什么,你想如何使用它?
    • 这只是一个面具。例如:array([ True, True, True, ..., True, True, True], dtype=bool)