擅长:python、mysql、java
<p>您可以尝试以下方法:</p>
<pre><code>import pandas as pd
df = pd.DataFrame(
{
'ID': ['AB01', 'AB02', 'AB02', 'AB01', 'AB01'],
'Values': [57, 98, 87, 69, 98],
'A': ['Type A', 'Type B', 'Type B', 'Type B', 'Type AB'],
'B': [None, 'Type AB', None, 'Type A', None]
}
)
df.loc[(df[['A', 'B']] == 'Type AB').any(axis=1), 'C'] = 'Present'
df
</code></pre>
<p>出去</p>
<pre><code> ID Values A B C
0 AB01 57 Type A None NaN
1 AB02 98 Type B Type AB Present
2 AB02 87 Type B None NaN
3 AB01 69 Type B Type A NaN
4 AB01 98 Type AB None Present
</code></pre>
<p>如果您的检查比精确相等匹配稍微复杂一些,则可以创建更健壮的索引掩码。这里我检查A列或B列中是否有任何字符串包含子字符串“AB”:</p>
<pre><code>match_mask = df[['A', 'B']].apply(lambda x: x.str.contains('AB')).any(axis=1)
df.loc[match_mask, 'C'] = 'Present'
</code></pre>