Python Pandas: Check if string in one column is contained in string of another column in the same row

You need apply with in:

df['C'] = df.apply(lambda x: x.A in x.B, axis=1)
print (df)
   RecID  A    B      C
0      1  a  abc   True
1      2  b  cba   True
2      3  c  bca   True
3      4  d  bac  False
4      5  e  abc  False

Another solution with list comprehension is faster, but there has to be no NaNs:

df['C'] = [x[0] in x[1] for x in zip(df['A'], df['B'])]
print (df)
   RecID  A    B      C
0      1  a  abc   True
1      2  b  cba   True
2      3  c  bca   True
3      4  d  bac  False
4      5  e  abc  False

I could not get either answer @jezreal provided to handle None's in the first column. A slight alteration to the list comprehension is able to handle it:

[x[0] in x[1] if x[0] is not None else False for x in zip(df['A'], df['B'])]

Tags:

Python

Pandas