9

I have a data-frame with multi-index like this:

Date      Period     Value \n
20130101    0          12 \n
20130101    1          13
20130102    0          13
20130102    1          14

The first level is Date and the second level is period. I would like to set the values where the period is not zero to zero, the output would be something like this:

Date      Period     Value
20130101    0          12
20130101    1          0
20130102    0          13
20130102    1          0

If the second level was a column as opposed to index, the solution would be easy df.Value.loc[df.Period == 0] =0.

Is there a way to achieve this, by just using index?

MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419
motam79
  • 3,542
  • 5
  • 34
  • 60

1 Answers1

10

try this:

df.loc[df.index.get_level_values('Period') != 0, 'Value'] = 0

Explanation:

In [5]: df
Out[5]:
                 Value
Date     Period
20130101 0          12
         1          13
20130102 0          13
         1          14

In [6]: df.index.get_level_values('Period')
Out[6]: Int64Index([0, 1, 0, 1], dtype='int64', name='Period')

In [7]: df.index.get_level_values('Period') != 0
Out[7]: array([False,  True, False,  True], dtype=bool)

In [8]: df[df.index.get_level_values('Period') != 0]
Out[8]:
                 Value
Date     Period
20130101 1          13
20130102 1          14

In [9]: df.loc[df.index.get_level_values('Period') != 0, 'Value'] = 0

In [10]: df
Out[10]:
                 Value
Date     Period
20130101 0          12
         1           0
20130102 0          13
         1           0
MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419