0
0
PandasHow-ToBeginner · 3 min read

How to Use str.upper in pandas to Convert Text to Uppercase

In pandas, use Series.str.upper() to convert all string values in a column to uppercase letters. This method works on string columns and returns a new Series with uppercase text.
📐

Syntax

The syntax for converting text to uppercase in a pandas Series is:

  • Series.str.upper(): Applies uppercase conversion to each string element in the Series.

This method returns a new Series with all characters converted to uppercase.

python
df['column_name'].str.upper()
💻

Example

This example shows how to convert a DataFrame column with names to uppercase using str.upper().

python
import pandas as pd

data = {'Name': ['alice', 'Bob', 'charlie', 'David']}
df = pd.DataFrame(data)

# Convert 'Name' column to uppercase
uppercase_names = df['Name'].str.upper()

print(uppercase_names)
Output
0 ALICE 1 BOB 2 CHARLIE 3 DAVID Name: Name, dtype: object
⚠️

Common Pitfalls

Common mistakes when using str.upper() include:

  • Trying to use upper() directly on a pandas Series without str accessor, which causes an error.
  • Applying str.upper() on columns with non-string data types without converting them first.

Always use str.upper() on string columns or convert data to strings first.

python
import pandas as pd

data = {'Mixed': ['apple', 123, None, 'Banana']}
df = pd.DataFrame(data)

# Wrong: This will raise an error
# df['Mixed'].upper()

# Right: Use str accessor and convert to string first
uppercase_mixed = df['Mixed'].astype(str).str.upper()
print(uppercase_mixed)
Output
0 APPLE 1 123 2 NONE 3 BANANA Name: Mixed, dtype: object
📊

Quick Reference

MethodDescription
Series.str.upper()Convert all string characters in the Series to uppercase.
Series.str.lower()Convert all string characters in the Series to lowercase.
Series.astype(str)Convert Series elements to string type before applying string methods.

Key Takeaways

Use Series.str.upper() to convert text in pandas columns to uppercase.
Always use the str accessor before string methods on pandas Series.
Convert non-string data to string first to avoid errors with str.upper().
str.upper() returns a new Series; it does not modify the original data in place.
Combine astype(str) with str.upper() for mixed-type columns.