Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas multi-index how to mask the data by the second level

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?

like image 583
motam79 Avatar asked Apr 13 '16 19:04

motam79


1 Answers

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
like image 102
MaxU - stop WAR against UA Avatar answered Oct 26 '22 17:10

MaxU - stop WAR against UA