6

I have a column in a pandas dataframe that is all capitals. I would like to change this to words with only the first letter capitalized.

I have tried the following:

import pandas as pd
data = pd.read_csv('my_file.csv')

data['field'] = data['field'].title()

This returns the error:

'Series' object has no attribute 'title'

Is there a simple way to perform string operations like this on a pandas column?

datavoredan
  • 3,136
  • 6
  • 29
  • 45

2 Answers2

10

Found the answer here:

http://pandas.pydata.org/pandas-docs/stable/text.html

data['field'] = data['field'].str.title()
datavoredan
  • 3,136
  • 6
  • 29
  • 45
5

An alternative solution using a list comprehension:

data['field'] = [word.title() for word in data['field']]

Timings

df = pd.DataFrame({'field': ['abc', 'def', 'ghi'] * 100000})

%timeit df['field'].str.title()
10 loops, best of 3: 89.3 ms per loop

%timeit [word.title() for word in df['field']]
10 loops, best of 3: 52.6 ms per loop
Pedram
  • 3,485
  • 3
  • 17
  • 32
Alexander
  • 96,739
  • 27
  • 183
  • 184