Pandas DataFrame isin() method with examples

Spread the love

The isin() method in pandas is used to filter a dataframe. It is used to check if the object contains the elements from list, Series, Dict. It returns True if it contains the values otherwise returns False.

Syntax –

dataframe.isin(values)

Examples –

Let’s read a dataset to illustrate it.

import pandas as pd

url = 'https://raw.githubusercontent.com/bprasad26/lwd/master/data/clothing_store_sales.csv'
df = pd.read_csv(url)
df.head()

1 . Using a single value –

Let’s say I want to select all the rows from the dataframe where the Method of Payment is MasterCard. For this I can use the isin method.

df['Method of Payment'].isin(['MasterCard'])

The above code checks whether the Method of Payment column contains the value “MasterCard“. If it contains then it return True otherwise it returns False. Now we can use the boolean series to filter the dataframe.

df[df['Method of Payment'].isin(['MasterCard'])].head()

2 . Using a List of Values –

We can also pass multiple values. Let’s say we want to select all the rows from the dataframe where the Method of Payment is MasterCard or Discover.

df[df['Method of Payment'].isin(['MasterCard', 'Discover'])].head()

3. Does not contains the List of Values –

We can also check whether a column does not contains a list of values. Let’s say we want to select all rows where Method of Payment is not MasterCard or Discover. It is the opposite of the above recipe. To do this we use the tilda (~) operator.

df[~df['Method of Payment'].isin(['MasterCard', 'Discover'])].head()

Rating: 1 out of 5.

Leave a Reply