Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas DataFrame, how to apply function to a specific column?

Tags:

python

pandas

I have read the docs of DataFrame.apply

DataFrame.apply(func, axis=0, broadcast=False, raw=False, reduce=None, args=(), **kwds)¶ Applies function along input axis of DataFrame.

So, How can I apply a function to a specific column?

In [1]: import pandas as pd In [2]: data = {'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]} In [3]: df = pd.DataFrame(data) In [4]: df Out[4]:     A  B  C 0  1  4  7 1  2  5  8 2  3  6  9 In [5]: def addOne(v): ...:        v += 1 ...:        return v ...:  In [6]: df.apply(addOne, axis=1) Out[6]:     A  B   C 0  2  5   8 1  3  6   9 2  4  7  10 

I want to addOne to every value in df['A'], not all columns. How can I do that with DataFrame.apply.

Thanks for help!

like image 392
GoingMyWay Avatar asked Mar 25 '16 03:03

GoingMyWay


People also ask

How do you apply a function to all values in a DataFrame column?

The apply() function is used to apply a function along an axis of the DataFrame. Objects passed to the function are Series objects whose index is either the DataFrame's index (axis=0) or the DataFrame's columns (axis=1).

What is apply () in pandas?

The apply() method allows you to apply a function along one of the axis of the DataFrame, default 0, which is the index (row) axis.

How do I assign a value to a column in pandas?

You can set cell value of pandas dataframe using df.at[row_label, column_label] = 'Cell Value'. It is the fastest method to set the value of the cell of the pandas dataframe. Dataframe at property of the dataframe allows you to access the single value of the row/column pair using the row and column labels.


1 Answers

The answer is,

df['A'] = df['A'].map(addOne) 

and maybe you would be better to know about the difference of map, applymap, apply.

but if you insist to use apply, you could try like below.

def addOne(v):     v['A'] += 1     return v  df.apply(addOne, axis=1) 
like image 118
su79eu7k Avatar answered Sep 21 '22 10:09

su79eu7k