【发布时间】:2018-12-18 11:32:13
【问题描述】:
我有一个数据框,我想用多索引系列的布尔值屏蔽(转换为 NaN),其中系列的多索引也是数据框中的列名。例如,如果df 是:
df = pd.DataFrame({ 'A': (188, 750, 1330, 1385, 188, 750, 810, 1330, 1385),
'B': (1, 2, 4, 5, 1, 2, 3, 4, 5),
'C': (2, 5, 7, 2, 5, 5, 3, 7, 2),
'D': ('foo', 'foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'bar', 'bar') })
A B C D
0 188 1 2 foo
1 750 2 5 foo
2 1330 4 7 foo
3 1385 5 2 foo
4 188 1 5 bar
5 750 2 5 bar
6 810 3 3 bar
7 1330 4 7 bar
8 1385 5 2 bar
而多索引系列ser 是:
arrays = [('188', '750', '810', '1330', '1385'),
('1', '2', '3', '4', '5')]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['A', 'B'])
ser = pd.Series([False, False, True, False, True], index=index)
A B
188 1 False
750 2 False
810 3 True
1330 4 False
1385 5 True
dtype: bool
如何屏蔽(转换为 NaN)df 中的列 C 上的值,其中条目为系列 False 中的 ser,以便以最终的 Dataframe 结束,如下所示:
A B C D
0 188 1 2 foo
1 750 2 5 foo
2 1330 4 7 foo
3 1385 5 NaN foo
4 188 1 5 bar
5 750 2 5 bar
6 810 3 NaN bar
7 1330 4 7 bar
8 1385 5 NaN bar
【问题讨论】:
标签: python python-3.x pandas dataframe multi-index