3

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.

1 Answer 1

2

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())
Sign up to request clarification or add additional context in comments.

4 Comments

It's also worth mentioning that vectorized string operations don't always outperform regular Python loops. Even when they do, the difference is not that much. Pandas handles labels/NaNs for you though.
@piRSquared side q: when you iterate over s in the list comp, the iterator returns each row one at a time?
The way you wrote s implies that it is a Series. In that case, yes, the comprehension iterates one element of the series' values at a time.
@piRSquared I am late but is there more efficient way to do the same ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.