While using Pandas, I often encounter a case where there is an existing function which takes in multiple arguments and returns multiple values:
def foo(val_a, val_b):
"""
Some example function that takes in and returns multiple values.
Can be a lot more complex.
"""
sm = val_a + val_b
sb = val_a - val_b
mt = val_a * val_b
dv = val_a / val_b
return sm, sb, mt, dv
Suppose I have a dataframe:
import pandas as pd
df = pd.DataFrame([[1, 2], [3, 4], [5, 6], [7, 8]])
df
Out[6]:
0 1
0 1 2
1 3 4
2 5 6
3 7 8
What I want is to apply foo on df with column 0 and 1 as arguments, and put the results into new columns of df, without modifying foo, like this:
df_out
Out[7]:
0 1 su sb mt dv
0 1 2 3 -1 2 0.5
1 3 4 7 -1 12 0.75
2 5 6 11 -1 30 0.833
3 7 8 15 -1 56 0.875
What is the most pythonic way to achieve this?