Pandas DataFrame isin() Method.


Pandas DataFrame isin() Method.

Table Of Contents:

  1. Syntax isin( ) Method.
  2. Examples isin( ) Method.

(1) Syntax:

DataFrame.isin(values)

Description:

  • The isin() method checks if the Dataframe contains the specified value(s).
  • It returns a DataFrame similar to the original DataFrame, but the original values have been replaced with True if the value was one of the specified values, otherwise False.

Parameters:

  • values: iterable, Series, DataFrame or dict –  – The result will only be true at a location if all the labels match. If values is a Series, that’s the index. If values is a dict, the keys must be the column names, which must match. If values is a DataFrame, then both the index and column labels must match.

Returns:

  • DataFrame – DataFrame of booleans showing whether each element in the DataFrame is contained in values.

(2) Examples Of items() Method:

Example-1

import pandas as pd

data = {
  "name": ["Sally", "Mary", "John"],
  "age": [50, 40, 30]
}

df = pd.DataFrame(data)

df

Output:

df.isin([50, 30])
df[df.isin([50, 30])]

Example-2

df = pd.DataFrame({'num_legs': [2, 4], 'num_wings': [2, 0]},
                  index=['falcon', 'dog'])
df

Output:

df.isin([0, 2])

Output:

To check if values is not in the DataFrame, use the ~ operator:

~df.isin([0, 2])

Output:

When values is a dict, we can pass values to check for each column separately:

df.isin({'num_wings': [0, 3]})

Output:

When values is a Series or DataFrame the index and column must match. Note that ‘falcon’ does not match based on the number of legs in other.

other = pd.DataFrame({'num_legs': [8, 3], 'num_wings': [0, 2]},
                     index=['spider', 'falcon'])

df.isin(other)

Output:

Leave a Reply

Your email address will not be published. Required fields are marked *