pandas 多索引如何通过第二层掩盖数据 [英] pandas multi-index how to mask the data by the second level
本文介绍了 pandas 多索引如何通过第二层掩盖数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个具有多重索引的数据框,如下所示:
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
如果第二级是与索引相对的一列,则解决方案将很容易df.Value.loc[df.Period == 0] =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?
推荐答案
尝试一下:
df.loc[df.index.get_level_values('Period') != 0, 'Value'] = 0
说明:
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
这篇关于 pandas 多索引如何通过第二层掩盖数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文