Monday, 29 January 2024

Pandas: Convert all the column values to title case

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

Example

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

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

 

Find the below working application.

 

title_case.py

import pandas as pd

# Create a sample DataFrame
data = {'Name': ['krishna gurram', 'sailu nava', 'joel chelli', 'chamu mag', 'Jitendra khod', "Krishna battu"],
        '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.title()

print('\nDataFrame after converting the names to title case \n', df)

Output

Original DataFrame
             Name  Age       City  Gender  Rating
0  krishna gurram   34  Bangalore    Male      67
1      sailu nava   35  Hyderabad  Female      43
2     joel chelli  234  Hyderabad    Male      67
3       chamu mag   35    Chennai  Female     100
4   Jitendra khod   52  Bangalore    Male      41
5   Krishna battu   34    Chennai    Male      89

DataFrame after converting the names to title case 
              Name  Age       City  Gender  Rating
0  Krishna Gurram   34  Bangalore    Male      67
1      Sailu Nava   35  Hyderabad  Female      43
2     Joel Chelli  234  Hyderabad    Male      67
3       Chamu Mag   35    Chennai  Female     100
4   Jitendra Khod   52  Bangalore    Male      41
5   Krishna Battu   34    Chennai    Male      89

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment