DEV Community

Cover image for How to Capitalize String Python Dataframe Pandas
saim
saim

Posted on Originally published at pleypot.com

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.

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)
Enter fullscreen mode Exit fullscreen mode

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.

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)
Enter fullscreen mode Exit fullscreen mode

This will the output.

       text
0  Hello World
1  Python Programming
2     Pandas
Enter fullscreen mode Exit fullscreen mode

Top comments (0)