简体   繁体   中英

pandas - perform string operation on all elements of a column

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?

Found the answer here:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM