Xavier Sun
Xavier Sun

Reputation: 89

How to search/compare the integer of Column 1 in the list-type Column 2 in Dataframe?

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.

enter image description here

Eventually I would expect to get the Result Column as like below:

enter image description here

Is there any better way to get the expected result in Python Pandas? Thanks!

Upvotes: 1

Views: 130

Answers (1)

jezrael
jezrael

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

Related Questions