Tuesday, 14 November 2023

Perform multi value search in a dataframe using isin method

The isin() method allows you to compare multiple values in a Series.

Example

interested_cities = ['Bangalore', 'Chennai']
interested_cities_bool_series = df['City'].isin(interested_cities)
interested_rows = df[interested_cities_bool_series]

 Above snippet get all the persons details whose City is 'Bangalore', or 'Chennai'.

Find the working application.

is_in_demo.py

import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Krishna', 'Sailu', 'Joel', 'Chamu', 'Jitendra', "Raj"],
        'Age': [34, 35, 29, 35, 52, 34],
        'City': ['Bangalore', 'Hyderabad', 'Hyderabad', 'Chennai', 'Bangalore', 'Chennai'],
        'Gender': ['Male', 'Female', 'Male', 'Female', 'Male', 'Male'],
        'Percentage': [81, 76, 67, 100, 87, 89]}
df = pd.DataFrame(data)
print('Original DataFrame')
print(df)

print('\nPersons staying in the City Bangalore or Cheannai')
interested_cities = ['Bangalore', 'Chennai']
interested_cities_bool_series = df['City'].isin(interested_cities)
interested_rows = df[interested_cities_bool_series]
print(df[interested_cities_bool_series])

Output

Original DataFrame
       Name  Age       City  Gender  Percentage
0   Krishna   34  Bangalore    Male          81
1     Sailu   35  Hyderabad  Female          76
2      Joel   29  Hyderabad    Male          67
3     Chamu   35    Chennai  Female         100
4  Jitendra   52  Bangalore    Male          87
5       Raj   34    Chennai    Male          89

Persons staying in the City Bangalore or Cheannai
       Name  Age       City  Gender  Percentage
0   Krishna   34  Bangalore    Male          81
3     Chamu   35    Chennai  Female         100
4  Jitendra   52  Bangalore    Male          87
5       Raj   34    Chennai    Male          89







Previous                                                 Next                                                 Home

No comments:

Post a Comment