<h3>溶液</h3>
<pre><code>m = test['cosine'].eq('Na') & \
test['target'].isin(list_w) & \
test['condition'].isin(['weak', 'strong'])
i1 = test.set_index(['isi', 'target', 'condition']).index
i2 = test[m].set_index(['isi', 'target', test.loc[m, 'condition'].radd('unrel_')]).index
test['revised_cosine'] = test['cosine'].mask(i1.isin(i2), 'Na')
</code></pre>
<h3>解释</h3>
<p>让我们创建一个布尔掩码<code>m</code>,当<code>cosine</code>列包含<code>Na</code>时,它保存<code>True</code>,同时<code>target</code>列包含来自<code>list_w</code>的一个单词,而<code>condition</code>列是<code>weak</code>或<code>strong</code></p>
<pre><code>>>> m
0 False
1 False
2 True
3 True
4 False
5 False
6 False
7 False
8 True
9 True
10 False
11 False
12 False
13 False
14 False
15 False
dtype: bool
</code></pre>
<p>基于<code>isi</code>、<code>target</code>和<code>condition</code>列创建一个<code>MultiIndex</code>,我们将其称为<code>i1</code>。使用掩码<code>m</code>过滤<code>test</code>数据帧中的行,向<code>condition</code>列中过滤的行添加前缀<code>unrel_</code>,并以类似方式创建另一个多索引<code>i2</code></p>
<pre><code>>>> i1
MultiIndex([( 50, 'monthly', 'strong'),
(1050, 'monthly', 'strong'),
( 50, 'monthly', 'weak'),
(1050, 'monthly', 'weak'),
( 50, 'monthly', 'unrel_strong'),
(1050, 'monthly', 'unrel_strong'),
( 50, 'monthly', 'unrel_weak'),
(1050, 'monthly', 'unrel_weak'),
( 50, 'moon', 'strong'),
(1050, 'moon', 'strong'),
( 50, 'moon', 'weak'),
(1050, 'moon', 'weak'),
( 50, 'moon', 'unrel_strong'),
(1050, 'moon', 'unrel_strong'),
( 50, 'moon', 'unrel_weak'),
(1050, 'moon', 'unrel_weak')],
names=['isi', 'target', 'condition'])
>>> i2
MultiIndex([( 50, 'monthly', 'unrel_weak'),
(1050, 'monthly', 'unrel_weak'),
( 50, 'moon', 'unrel_strong'),
(1050, 'moon', 'unrel_strong')],
names=['isi', 'target', 'condition'])
</code></pre>
<p><code>Mask</code>使用布尔掩码在<code>cosine</code>列中创建值,该掩码可以通过测试<code>i2</code>中<code>i1</code>的成员身份来创建</p>
<pre><code> isi prime target condition meanRT cosine revised_cosine
0 50 weekly monthly strong 676.2 0.9 0.9
1 1050 weekly monthly strong 643.5 0.9 0.9
2 50 daily monthly weak 737.2 Na Na
3 1050 daily monthly weak 670.6 Na Na
4 50 bathtub monthly unrel_strong 692.2 0.1 0.1
5 1050 bathtub monthly unrel_strong 719.1 0.1 0.1
6 50 sponge monthly unrel_weak 805.8 0.3 Na
7 1050 sponge monthly unrel_weak 685.7 0.3 Na
8 50 crescent moon strong 625.0 Na Na
9 1050 crescent moon strong 537.2 Na Na
10 50 sunset moon weak 698.4 0.2 0.2
11 1050 sunset moon weak 704.3 0.2 0.2
12 50 premises moon unrel_strong 779.2 0.7 Na
13 1050 premises moon unrel_strong 647.6 0.7 Na
14 50 descent moon unrel_weak 686.0 0.5 0.5
15 1050 descent moon unrel_weak 725.4 0.5 0.5
</code></pre>