Is there a way in python pandas to apply a conditional if one or another column have a value?
For one column, I know I can use the following code, to apply a test flag if the column Title includes the word "test".
df['Test_Flag'] = np.where(df['Title'].str.contains("test|Test"), 'Y', '')
But if I would like to say if column title or column subtitle include the word "test", add the test flag, how could I do that?
This obviously didn't work
df['Test_Flag'] = np.where(df['Title'|'Subtitle'].str.contains("test|Test"), 'Y', '')
If many columns then simplier is create subset df[['Title', 'Subtitle']] and apply contains, because works only with Series and check at least one True per row by any:
mask = df[['Title', 'Subtitle']].apply(lambda x: x.str.contains("test|Test")).any(axis=1)
df['Test_Flag'] = np.where(mask,'Y', '')
Sample:
df = pd.DataFrame({'Title':['test','Test','e', 'a'], 'Subtitle':['b','a','Test', 'a']})
mask = df[['Title', 'Subtitle']].apply(lambda x: x.str.contains("test|Test")).any(axis=1)
df['Test_Flag'] = np.where(mask,'Y', '')
print (df)
Subtitle Title Test_Flag
0 b test Y
1 a Test Y
2 Test e Y
3 a a
pattern = "test|Test"
match = df['Title'].str.contains(pattern) | df['Subtitle'].str.contains(pattern)
df['Test_Flag'] = np.where(match, 'Y', '')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With