eljusticiero67 eljusticiero67 - 1 year ago 125
Python Question

Apply function to each cell in DataFrame

I have a dataframe that may look like this:

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')

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.

Answer Source

You can do df%2, with the old question about finding the even numbers in the data frame:

df%2 == 0

#    A        B       C
#0  True    False   True
#1  False   True    False


Since the question has been updated, as per @ayhan suggested, you can use applymap() which is concise for your case.


#     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
#     A       B       C
#0  wow     bar wow bar
#1  bar wow wow     bar
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download