0

I need to combine different functions into one and use the apply function(of those individual functions) within the main function itself. My case is something more complex so i'll use a basic example for this.

Suppose i have a data consisting of numbers. Lets call it "MathData". The column containing the 2 numbers is called 'digits'.

Here are my individual functions:

def add(nm1,nm2):
    sum = nm1+nm2
    return sum
MathData['sum'] = Mathdata['digits'].apply(add) #gives me new column called "sum" with the sum of each observation in it.   

Similarly,

def diff(nm1,nm2):
    subtract = nm1-nm2
    return subtract

def mul(nm1,nm2):
    multiply = nm1 * nm2
    return multiply

def div(nm1,nm2):
    divide = nm1/nm2
    return divide


MathData['difference'] = Mathdata['digits'].apply(diff)
MathData['product'] = Mathdata['digits'].apply(mul)
MathData['quotient'] = Mathdata['digits'].apply(div)

So I'd get different columns with the sum, diff,product,quotient etc.
I want all of these into 1 function with each value in different columns.

def mathop(nm1,nm2):
    sum = nm1+nm2
    diff = nm1-nm2
    mul = nm1*nm2
    div = nm1/nm2
    return sum,diff,mul,div

The above function would give me all values in a single column separated by commas. is there a way to apply each one in such a way that they come under different columns??

1

1 Answer 1

0

I do not know the pandas module, but in pure Python you could do something like this:

import operator
mathops = {'sum': operator.sum,
           'diff': operator.sub,
           'mul': operator.mul,
           'div': operator.div}

for op_name, op in mathops:
    MathData[op_name] = MathData['digits'].apply(op)
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.