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,536
  • 9
  • 32
  • 48

2 Answers2

10

Found the answer here:

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

data['field'] = data['field'].str.title()
datavoredan
  • 3,536
  • 9
  • 32
  • 48
6

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 Parsian
  • 3,750
  • 3
  • 19
  • 34
Alexander
  • 105,104
  • 32
  • 201
  • 196