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

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay