0
0
Pandasdata~5 mins

isin() for value matching in Pandas

Choose your learning style9 modes available
Introduction

We use isin() to quickly check if values in a list or column match any values from another list. It helps us filter or find data easily.

You want to find all rows in a table where a column has certain values.
You have a list of favorite items and want to see which ones appear in your data.
You want to filter data to only include specific categories or groups.
You want to mark or flag data points that belong to a set of interest.
Syntax
Pandas
DataFrame['column_name'].isin([value1, value2, ...])

This returns a series of True/False showing if each value is in the list.

You can use this result to filter rows or create new columns.

Examples
Check if each fruit in the 'fruit' column is either 'apple' or 'banana'.
Pandas
df['fruit'].isin(['apple', 'banana'])
Filter rows where the 'color' column is 'red' or 'blue'.
Pandas
df[df['color'].isin(['red', 'blue'])]
Create a new column marking if 'item' is in the favorite list.
Pandas
df['is_favorite'] = df['item'].isin(['pen', 'notebook'])
Sample Program

This code creates a small table of people and their cities. Then it finds who lives in New York or Chicago using isin(). Finally, it shows only those people.

Pandas
import pandas as pd

data = {'name': ['Alice', 'Bob', 'Charlie', 'David'],
        'city': ['New York', 'Los Angeles', 'New York', 'Chicago']}
df = pd.DataFrame(data)

# We want to find people who live in New York or Chicago
cities_to_find = ['New York', 'Chicago']

# Use isin() to check
mask = df['city'].isin(cities_to_find)

# Filter the DataFrame
filtered_df = df[mask]

print(filtered_df)
OutputSuccess
Important Notes

isin() works with lists, sets, or any iterable of values.

It is case-sensitive when matching strings.

You can combine isin() with other conditions for more complex filters.

Summary

isin() helps find if values belong to a list.

It returns True or False for each value checked.

Use it to filter or mark data easily.