简体   繁体   中英

Create a new column with condition if a string 'contains' substring?

I want to add a new column 'check' with the following condition:

  • 'Suppression total' and 'Sup-SDM'.

OR

  • Suppression partiel and Franc SUP - Geisi

Dataframe :

Type Info
Sup_EF - SUP - SDM 2021-12-08 16:47:51.0-Suppression totale
Modif_EF - SUP - SDM 2021-12-08 16:47:51.0-Creation
Sup_EF - SUP - Geisi 2021-12-08 16:47:51.0-Suppression totale
Modif_EF - Franc SUP - Geisi 2021-12-17 10:50:40.0-Suppression partiel

Desired output :

Type Info Check
Sup_EF - SUP - SDM 2021-12-08 16:47:51.0-Suppression total Correct
Modif_EF - SUP - SDM 2021-12-08 16:47:51.0-Creation Fail
Sup_EF - SUP - Geisi 2021-12-08 16:47:51.0-Suppression total Fail
Modif_EF - Franc SUP - Geisi 2021-12-17 10:50:40.0-Suppression partiel Correct

Code :

if ('SUP - SDM' in df["Type"].values) and ('Suppression total' in df['Info'].values):
    df['Check'] = "Correct"
elif ('Franc SUP - Geisi' in df["Type"].values) and ('Suppression partiel' in df['Info'].values):
    df['Check'] = "Correct"
else:
    df['Check'] = "Fail"

But my output looks like this:

Type Info Check
Sup_EF - SUP - SDM 2021-12-08 16:47:51.0-Suppression total Fail
Modif_EF - SUP - SDM 2021-12-08 16:47:51.0-Creation Fail
Sup_EF - SUP - Geisi 2021-12-08 16:47:51.0-Suppression total Fail
Modif_EF - Franc SUP - Geisi 2021-12-17 10:50:40.0-Suppression partiel Fail

对于非常大的数据集,这种应用方法可能会很慢,但适用于一般目的

df['Check'] = df.apply(lambda x: 'Correct' if ('Suppression total' in x['Info'] and 'Sup-SDM' in x['Type']) or ('Suppression partiel' in x['Info'] and 'Franc SUP - Geisi' in x['Type']) else 'Fail')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM