38

How do you capitalize the first letter of each word in a pandas dataframe column? For example, I am trying to make the following transformation.

  Column1          Column1
The apple        The Apple
 the Pear   ⟶    The Pear
Green tea        Green Tea
cottontail
  • 10,268
  • 18
  • 50
  • 51
Jason Ching Yuk
  • 894
  • 2
  • 11
  • 30

2 Answers2

77

You can use str.title:

df.Column1 = df.Column1.str.title()
print(df.Column1)
0    The Apple
1     The Pear
2    Green Tea
Name: Column1, dtype: object

Another very similar method is str.capitalize, but it uppercases only first letters:

df.Column1 = df.Column1.str.capitalize()
print(df.Column1)
0    The apple
1     The pear
2    Green tea
Name: Column1, dtype: object
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
0

As pandas string methods are not optimized, mapping the equivalent Python string methods is often faster than pandas' .str methods. So for example, to capitalize the first letter of each word, the following may be used.

df['Column1'] = df['Column1'].map(str.title)

  Column1          Column1
The apple        The Apple
 the Pear   ⟶    The Pear
Green TEA        Green Tea

On the other hand, if you want to capitalize only the first character in each string, then calling upper() only on the first character works.

df['Column1'] = df['Column1'].str[:1].str.upper() + df['Column1'].str[1:]
# or 
df['Column1'] = df['Column1'].map(lambda x: x[:1].upper() + x[1:])

  Column1          Column1
The apple        The apple
 the Pear   ⟶    The Pear
Green TEA        Green TEA
cottontail
  • 10,268
  • 18
  • 50
  • 51