回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我有一个数据帧,我想用一个多索引序列的布尔值来屏蔽(转换为NaN),其中序列的多索引也是数据帧中的列名。例如,如果<code>df</code>是:</p>
<pre><code>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
</code></pre>
<p>多索引序列<code>ser</code>是:</p>
<pre><code>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
</code></pre>
<p>如何屏蔽(转换为NaN)列<code>C</code>中的值,其中条目是序列<code>ser</code>中的<code>False</code>,以便以如下所示的最终数据帧结束:</p>
<pre><code> 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
</code></pre>