Reputation: 89
I have one dataframe like below - and I would like to test if Column Number
is in the Column List of Numbers
for each row record.
Eventually I would expect to get the Result
Column as like below:
Is there any better way to get the expected result in Python Pandas? Thanks!
Upvotes: 1
Views: 130
Reputation: 862591
Use list comprehension with in
statement:
df['Result'] = [b in a for a, b in df[['List of Numbers','Number']].values]
Similar idea with zip
:
df['Result'] = [b in a for a, b in zip(df['List of Numbers'],df['Number'])]
Or solution with DataFrame.apply
:
df['Result'] = df.apply(lambda x: x['Number'] in x['List of Numbers'], axis=1)
EDIT: Change df['Result']
to mask for any solutions above and filter by boolean indexing
:
mask = df.apply(lambda x: x['Number'] in x['List of Numbers'], axis=1)
df1 = df[mask]
Upvotes: 1