Thursday 1 February 2024

Pandas: Filter Dataframe rows using endswith method

'endswith' method can be applied on a DataFrame column to check whether particular value ends with given string or not.

 

Example

name_ends_with_a = df['Name'].str.lower().str.endswith('a')
persons_name_ends_with_a = df[name_ends_with_a]

The endswith() method is applied to the 'Name' column with the substring 'a'. It returns a Boolean Series where True indicates that the string in that particular column ends with the specified substring 'k', else False.

 

endswith.py

import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Krishna', 'Sailu', 'Joel', 'kranthi', 'Jitendra', "Kumar"],
        'Age': [34, 35, 234, 35, 52, 34],
        'City': ['Bangalore', 'Hyderabad', 'Hyderabad', 'Chennai', 'Bangalore', 'Chennai'],
        'Hobbies': ['Football,Cricket', 'Tennis, cricket', 'Trekking, reading books', 'Chess', 'Read Books', 'Cricket']}
df = pd.DataFrame(data)
print('Original DataFrame')
print(df)

# Get a boolean series to find the names ends with a (case insensitive)
name_ends_with_a = df['Name'].str.lower().str.endswith('a')
print('\nname_ends_with_a\n', name_ends_with_a)

persons_name_ends_with_a = df[name_ends_with_a]
print('\npersons_name_ends_with_a\n', persons_name_ends_with_a)

Output

Original DataFrame
       Name  Age       City                  Hobbies
0   Krishna   34  Bangalore         Football,Cricket
1     Sailu   35  Hyderabad          Tennis, cricket
2      Joel  234  Hyderabad  Trekking, reading books
3   kranthi   35    Chennai                    Chess
4  Jitendra   52  Bangalore               Read Books
5     Kumar   34    Chennai                  Cricket

name_ends_with_a
 0     True
1    False
2    False
3    False
4     True
5    False
Name: Name, dtype: bool

persons_name_ends_with_a
        Name  Age       City           Hobbies
0   Krishna   34  Bangalore  Football,Cricket
4  Jitendra   52  Bangalore        Read Books




  

Previous                                                 Next                                                 Home

No comments:

Post a Comment