简体   繁体   中英

Setting values of multiindex dataframe using only one-level indexing

My question is a logical continuation of this topic: Setting values with multiindex in pandas . So the example and answer from this, suits my situation either.

They set a multiindex value with f.loc[(slice(None), "one"), 0] = 1

But in my case, i have lot's of dataframes with custom number of index levels , so i would like to use indexing only on last level, without specifying others - smth like f.loc[:::, "one"), 0] = 1 . PS Also, if i have an Indexer for column "one", am i able to use it? Indexer can be an array: array([ True, True, True, ..., True, True, True], dtype=bool)

IIUC you want to use pd.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

boolean indexing using 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM