Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying function with multiple arguments to create a new pandas column

Tags:

python

pandas

I want to create a new column in a pandas data frame by applying a function to two existing columns. Following this answer I've been able to create a new column when I only need one column as an argument:

import pandas as pd df = pd.DataFrame({"A": [10,20,30], "B": [20, 30, 10]})  def fx(x):     return x * x  print(df) df['newcolumn'] = df.A.apply(fx) print(df) 

However, I cannot figure out how to do the same thing when the function requires multiple arguments. For example, how do I create a new column by passing column A and column B to the function below?

def fxy(x, y):     return x * y 
like image 369
Michael Avatar asked Nov 11 '13 20:11

Michael


People also ask

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

Pandas Apply Function to Single Column We will create a function add_3() which adds value 3 column value and use this on apply() function. To apply it to a single column, qualify the column name using df["col_name"] . The below example applies a function to a column B .


1 Answers

You can go with @greenAfrican example, if it's possible for you to rewrite your function. But if you don't want to rewrite your function, you can wrap it into anonymous function inside apply, like this:

>>> def fxy(x, y): ...     return x * y  >>> df['newcolumn'] = df.apply(lambda x: fxy(x['A'], x['B']), axis=1) >>> df     A   B  newcolumn 0  10  20        200 1  20  30        600 2  30  10        300 
like image 98
Roman Pekar Avatar answered Oct 12 '22 01:10

Roman Pekar