How to Capitalize String Python Dataframe Pandas

There are two main ways to capitalize strings in a pandas DataFrame:

1. str.capitalize():

This method capitalizes the first letter of each word in a string element.

Python
import pandas as pd

# Create a DataFrame
df = pd.DataFrame({'text': ['hello world', 'python programming', 'pandas']})

# Capitalize the first letter of each word
df['text'] = df['text'].str.capitalize()

print(df)
Capitalize Dataframe Pandas

2. Vectorized string methods:

You can achieve capitalization using vectorized string methods like .str.upper() for uppercase and string slicing for selecting the first character.

Python
import pandas as pd

# Create a DataFrame
df = pd.DataFrame({'text': ['hello world', 'python programming', 'pandas']})

# Capitalize the first letter and lowercase the rest
df['text'] = df['text'].str[0].str.upper() + df['text'].str[1:].str.lower()

print(df)

This will the output.

output
       text
0  Hello World
1  Python Programming
2     Pandas