Thursday 1 February 2024

Pandas: Filter Dataframe rows using startswith method

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

 

Example

name_starts_with_k = df['Name'].str.lower().str.startswith('k')
persons_name_starts_with_k = df[name_starts_with_k]

 

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

 

startswith.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 starts with k (case insensitive)
name_starts_with_k = df['Name'].str.lower().str.startswith('k')
print('\nname_starts_with_k\n', name_starts_with_k)

persons_name_starts_with_k = df[name_starts_with_k]
print('\npersons_name_starts_with_k\n', persons_name_starts_with_k)

 

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_starts_with_k
 0     True
1    False
2    False
3     True
4    False
5     True
Name: Name, dtype: bool

persons_name_starts_with_k
       Name  Age       City           Hobbies
0  Krishna   34  Bangalore  Football,Cricket
3  kranthi   35    Chennai             Chess
5    Kumar   34    Chennai           Cricket

 

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment