Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python pandas column conditional on two other column values

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', '')
like image 585
jeangelj Avatar asked Apr 30 '26 09:04

jeangelj


2 Answers

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          
like image 103
jezrael Avatar answered May 01 '26 23:05

jezrael


pattern = "test|Test"
match = df['Title'].str.contains(pattern) | df['Subtitle'].str.contains(pattern)
df['Test_Flag'] = np.where(match, 'Y', '')
like image 33
Martin Valgur Avatar answered May 01 '26 23:05

Martin Valgur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!