Use A List Of Values To Select Rows From A Pandas Dataframe

To select rows from a Pandas dataframe using a list of values, you can use the isin() function. Here’s an example:

import pandas as pd

# Create a sample dataframe
data = {
    'Name': ['John', 'Smith', 'Alice', 'Bob', 'Mike'],
    'Age': [25, 30, 28, 35, 29],
    'City': ['New York', 'London', 'Paris', 'Tokyo', 'Sydney']

df = pd.DataFrame(data)

# List of values to select rows
selected_names = ['John', 'Alice', 'Mike']

# Use isin() function to select rows
selected_df = df[df['Name'].isin(selected_names)]

# Print the selected dataframe


   Name  Age     City
0  John   25  New York
2  Alice   28    Paris
4   Mike   29   Sydney

In this example, we have a dataframe df containing three columns: ‘Name’, ‘Age’, and ‘City’. We want to select rows where the ‘Name’ column matches any of the values in the selected_names list. To achieve this, we use the isin() function with the condition df['Name'].isin(selected_names) and pass it as a boolean index to the dataframe. The resulting selected dataframe is stored in selected_df and then printed.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!