Alex
Alex

Reputation: 1391

performing multiple string operations on a pandas Series/DataFrame

I would like to perform several operations on a particular Series. Is there a way to chain them without continually writing .str? ie if my series is called s and i want to do

s.str.replace("hi", "bye").str.strip().str.lower()

Is that the right way to do things? Seems verbose relative to R so I thought maybe there was a better syntax for this.

Upvotes: 3

Views: 2835

Answers (1)

piRSquared
piRSquared

Reputation: 294488

comprehension

Yes (sorta). Use a comprehension

[x.replace('hi', 'bye').strip().lower() for x in s]

Wrap that up into a series again.

pd.Series([x.replace('hi', 'bye').strip().lower() for x in s], s.index)

map

s.map(lambda x: x.replace('hi', 'bye').strip().lower())

Upvotes: 2

Related Questions