Pandas Series.str.capitalize() Method



The Series.str.capitalize() method in Pandas is used to capitalize the first character of each string in a Series or Index. This method is a convenient way to standardize the case of text data, ensuring that each string starts with an uppercase letter and the rest are in lowercase. This operation is similar to the string method str.capitalize() in Python.

Syntax

Following is the syntax of the Pandas Series.str.capitalize() method −

Series.str.capitalize()

Parameters

The Series.str.capitalize() method does not accept any parameters.

Return Value

The Series.str.capitalize() method returns a new Series with the first letter of each string capitalized and all other letters in lowercase.

Example 1

In this example, we demonstrate the basic usage of the Series.str.capitalize() method by applying it to a Series of strings.

import pandas as pd

# Create a Series of strings
s = pd.Series(['hi,', 'welcome to', 'tutorialspoint'])

# Display the input Series
print("Input Series")
print(s)

# Capitalize the first letter of each string
print("Series after calling the Capitalize:")
print(s.str.capitalize())

When we run the above code, it produces the following output

Input Series
0               hi,
1        welcome to
2    tutorialspoint
dtype: object

Series after calling the Capitalize:
0               Hi,
1        Welcome to
2    Tutorialspoint
dtype: object

Example 2

This example demonstrates how to use the Series.str.capitalize() method to format the 'Day' column in a DataFrame, converting each day's name to proper capitalization.

import pandas as pd

# Create a DataFrame
df = pd.DataFrame({'Day': ['mon', 'tue', 'wed', 'thu', 'fri'],
                   'Subject': ['Math', 'english', 'science', 'music', 'games']})

print("Input DataFrame:")
print(df)

# Capitalize the first letter of each day
df.Day = df.Day.str.capitalize()

print("DataFrame after applying Capitalize:")
print(df)

Following is the output of the above code −

Input DataFrame:
   Day  Subject
0  mon     Math
1  tue  english
2  wed  science
3  thu    music
4  fri    games
DataFrame after applying Capitalize:
   Day  Subject
0  Mon     Math
1  Tue  english
2  Wed  science
3  Thu    music
4  Fri    games

Example 3

In this example, we apply the Series.str.capitalize() method to an Index object. This showcases how you can use it to format the index labels in a DataFrame.

import pandas as pd

# Create a DataFrame with an Index
df = pd.DataFrame({'Value': [1, 2, 3]}, index=['first', 'second', 'third'])

# Capitalize the first letter of each index label
df.index = df.index.str.capitalize()

print(df)

Output of the above code is as follows −

       Value
First      1
Second     2
Third      3
python_pandas_working_with_text_data.htm
Advertisements