Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply function to each cell in DataFrame

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.

like image 377
eljusticiero67 Avatar asked Sep 13 '16 17:09

eljusticiero67


People also ask

How do you apply a function to every cell in a data frame?

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 .

How do I apply a function to each column in pandas?

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.

How do I apply a formula to an entire column in pandas?

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


1 Answers

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 
like image 114
Psidom Avatar answered Oct 05 '22 23:10

Psidom