Wednesday 24 January 2024

Pandas: Convert all the column values to lower case

'lower()' method converts the Strings in given column to lowercase and return a new series with the updated data.

Example

df['Name'] = df['Name'].str.lower()

As you see above snippet, we are using 'str' accessor to perform the string operations

 

Find the below working application.

 

lower.py

import pandas as pd

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

df['Name'] = df['Name'].str.lower()
df['City'] = df['City'].str.lower()
df['Gender'] = df['Gender'].str.lower()

print('\nDataFrame after lowering the string columns \n', df)

Output

Original DataFrame
       Name  Age       City  Gender  Rating
0   Krishna   34  Bangalore    Male      67
1     Sailu   35  Hyderabad  Female      43
2      Joel  234  Hyderabad    Male      67
3     Chamu   35    Chennai  Female     100
4  Jitendra   52  Bangalore    Male      41
5   Krishna   34    Chennai    Male      89

DataFrame after lowering the string columns 
        Name  Age       City  Gender  Rating
0   krishna   34  bangalore    male      67
1     sailu   35  hyderabad  female      43
2      joel  234  hyderabad    male      67
3     chamu   35    chennai  female     100
4  jitendra   52  bangalore    male      41
5   krishna   34    chennai    male      89



Previous                                                 Next                                                 Home

No comments:

Post a Comment