GenXeral
GenXeral

Reputation: 151

Creating Dataframe column using apply() in Python

Say you have a Table T with Columns A and B with numerical values. I want to create a new column C that gives me the ratio of A/B. I know the easy way to do this.

T['C']=T['A']/T['B']

But I want to try using the apply() function to a new copy of Table T. I have the following function below to execute this for any tables.

def ratio(T):
    X=T.copy()
    def ratio(a,b):
        return a/b
    X['C']=X['C'].apply(ratio,'A','B')
    return X

I get the KeyError: 'C' error. How do I properly get 'C' to exist in order to apply it/

Upvotes: 0

Views: 27

Answers (1)

Evan Nowak
Evan Nowak

Reputation: 895

You could simplify this with lambda:

X = T.copy()

X['C'] = T.apply(lambda row: row.A/row.B, axis=1)

Upvotes: 1

Related Questions