99
votes

I have a dataframe that may look like this:

A        B        C
foo      bar      foo bar
bar foo  foo      bar

I want to look through every element of each row (or every element of each column) and apply the following function to get the subsequent DF:

def foo_bar(x):
    return x.replace('foo', 'wow')

A        B        C
wow      bar      wow bar
bar wow  wow      bar

Is there a simple one-liner that can apply a function to each cell?

This is a simplistic example so there may be an easier way to execute this specific example other than applying a function, but what I am really asking about is how to apply a function in every cell within a dataframe.

1
I don't think it's a good idea to edit the questions to a completely new one, once you've already got answers to the old one as it would invalidate the prior answers to it. I would request you to roll back the original question and ask the new one separately.Nickil Maveli

1 Answers

142
votes

You can use applymap() which is concise for your case.

df.applymap(foo_bar)

#     A       B       C
#0  wow     bar wow bar
#1  bar wow wow     bar

Another option is to vectorize your function and then use apply method:

import numpy as np
df.apply(np.vectorize(foo_bar))
#     A       B       C
#0  wow     bar wow bar
#1  bar wow wow     bar