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.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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
Method 2
I guess you could use np.vectorize:
>>> df[:] = np.vectorize(foo_bar)(df)
>>> df
A B C
foo bar wow bar
bar wow wow bar
>>>
This might be quicker, since it’s using numpy.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0