2

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. P.S. 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)

Ladenkov Vladislav
  • 1,247
  • 2
  • 21
  • 45

1 Answers1

2

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
MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419