Explore Courses Blog Tutorials Interview Questions
0 votes
in Data Science by (17.6k points)

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


df['newcolumn'] = df.A.apply(fx)


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

1 Answer

0 votes
by (41.4k points)

This solves the problem:

df['newcolumn'] = df.A * df.B

You could also do:

def fab(row):

  return row['A'] * row['B']

df['newcolumn'] = df.apply(fab, axis=1)

Learn python with the help of this python training and also visit the python interview questions.

Browse Categories