Python Pandas: check if a row in one column is contained in a row of another column in the same row
I have a dataframe like this:
RecID| A |B
----------------
1 |a | abc
2 |b | cba
3 |c | bca
4 |d | bac
5 |e | abc
And want to create another column C from A and B so that for the same row, if the row in column A is contained in the row of column B, then C = True, and if not, then C = False.
The example output I'm looking for is the following:
RecID| A |B |C
--------------------
1 |a | abc |True
2 |b | cba |True
3 |c | bca |True
4 |d | bac |False
5 |e | abc |False
Is there a way to do this in pandas quickly and without using a loop? Thanks to
+17
source to share
2 answers
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 shouldn't be NaN
s:
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
+24
source to share