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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With