查找多列是否包含字符串

2024-06-25 06:53:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个带有ID、Value、a、B、C列的df。我想检查一个字符串,比如说“Type AB”,是否在a、B、C列的任何一行中。如果它存在,我想在新列“TypeAB_present”中为该行标记它“存在”。如何在python中实现这一点

enter image description here


Tags: 字符串标记iddfabvaluetypepresent
3条回答

您可以尝试以下方法:

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

出去

     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

如果您的检查比精确相等匹配稍微复杂一些,则可以创建更健壮的索引掩码。这里我检查A列或B列中是否有任何字符串包含子字符串“AB”:

match_mask = df[['A', 'B']].apply(lambda x: x.str.contains('AB')).any(axis=1)
df.loc[match_mask, 'C'] = 'Present'

尝试使用np.whereany

df['TypeAB _present'] = np.where(df[['A', 'B', 'C']].eq('Type AB').any(axis = 1 ), 'Present', '')

假设您正在使用pandas,并且正在从任何列中查找确切的“Type AB”标记

df['TypeAB_present'] = df[['A', 'B', 'C']].apply(lambda row: 'Present' if 'Type AB' in row.values else '', axis=1)

相关问题 更多 >