splinter
splinter

Reputation: 3907

Using apply on pandas dataframe with strings without looping over series

I have a pandas DataFrame filled with strings. I would like to apply a string operation to all entries, for example capitalize(). I know that for a series we can use series.str.capitlize(). I also know that I can loop over the column of the Dataframe and do this for each of the columns. But I want something more efficient and elegant, without looping. Thanks

Upvotes: 1

Views: 74

Answers (1)

piRSquared
piRSquared

Reputation: 294508

use stack + unstack
stack makes a dataframe with a single level column index into a series. You can then perform your str.capitalize() and unstack to get back your original form.

df.stack().str.capitalize().unstack()

Upvotes: 1

Related Questions