In this section we will be using title() function in pandas, to convert the character column of the python pandas dataframe to title case. We have listed some of different ways to convert string column to titlecase in pandas
- If the input string is in any case (upper, lower or title) , title() function in pandas converts the string to title case.
- use str.title() function to convert pandas column to titlecase
- use apply() function to convert pandas column to titlecase
- use apply() and lambda function to convert pandas string column to titlecase
- use map() function to convert pandas string column to titlecase
Create dataframe:
## create dataframe import pandas as pd d = {'Quarters' : ['quarter1','quarter2','quarter3','quarter4'], 'Description' : ['First Quarter of the year', 'second quarter of the year', 'Third Quarter of the year', 'FOURTH QUARTER OF THE YEAR']} df=pd.DataFrame(d) df
resultant dataframe will be
Convert pandas column to titlecase : str.title() function:
str.title() function first converts a column into string column and then into title case as shown below
### str.title() function df['Description_Title'] = df['Description'].str.title() df
Convert pandas column to titlecase : apply() function:
within apply() function string function is used and it converts the pandas column to title case as shown below
### apply() function df['Description_Title'] = df['Description'].apply(str.title) df
Convert pandas column to titlecase : apply() and lambda function:
within apply() function lambda function and string function is used to convert a column to title case in pandas dataframe as shown below
### apply() function & lambda function df['Description_Title'] = df['Description'].apply(lambda x: x.title()) df
Convert pandas column to titlecase : using map() function:
within map() function str.title() function is used to convert a column to title case in pandas dataframe as shown below
### map() function df['Description_Title'] = df['Description'].map(str.title) df