0

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/

1 Answer 1

1

You could simplify this with lambda:

X = T.copy()

X['C'] = T.apply(lambda row: row.A/row.B, axis=1)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.