Introduction
In this lab, we will learn about the pandas DataFrame isin() method. This method allows us to check whether each element in a DataFrame is contained in specified values. Applying this method to a DataFrame returns a new DataFrame of boolean values, where True indicates that the element is present in the specified values, and False indicates that it is not.
VM Tips
After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.
Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.
If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.
Import the necessary libraries
First, we need to import the pandas library:
import pandas as pd
Create a DataFrame
Next, let's create a DataFrame to demonstrate the isin() method:
df = pd.DataFrame({'a': [2, 4], 'b': [2, 0], 'c': [3, 5]})
Check values using the isin() method with a list
We can use the isin() method to check if each element in the DataFrame is present in a list of values. This returns a DataFrame of boolean values.
list_values = [2, 3]
df_1 = df.isin(list_values)
print(df_1)
Check values using the isin() method with a Series
We can also use the isin() method with a Series to check if each element in the DataFrame is present in the Series. This returns a DataFrame of boolean values.
series_values = pd.Series([2, 0, 3])
df_2 = df.isin(series_values)
print(df_2)
Check values using the isin() method with another DataFrame
The isin() method can also be used with another DataFrame to check if each element in the first DataFrame is present in the second DataFrame. This returns a DataFrame of boolean values.
df_3 = pd.DataFrame({'a': [0, 4], 'b': [1, 0], 'c': [3, 2]})
df_4 = df.isin(df_3)
print(df_4)
Check values using the isin() method with a dictionary
Finally, we can use the isin() method with a dictionary to check if each element in the DataFrame is present in the dictionary values. This returns a DataFrame of boolean values.
dict_values = {'a': [2, 1]}
df_5 = df.isin(dict_values)
print(df_5)
Summary
In this lab, we learned how to use the pandas DataFrame isin() method to check if each element in a DataFrame is contained in specified values. We saw examples of using the isin() method with lists, Series, other DataFrames, and dictionaries. The isin() method is a useful tool for filtering and manipulating DataFrame data based on specified values.