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.
By using apply() you call a function to every row of pandas DataFrame. Here the add() function will be applied to every row of pandas DataFrame. In order to iterate row by row in apply() function use axis=1 .
Python's Pandas Library provides an member function in Dataframe class to apply a function along the axis of the Dataframe i.e. along each row or column i.e. Important Arguments are: func : Function to be applied to each column or row. This function accepts a series and returns a series.
Pandas. dataframe. apply() function is used to apply the function along the axis of a DataFrame. Objects passed to that function are Series objects whose index is either a DataFrame's index (axis=0) or a DataFrame's columns (axis=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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With