Search code examples
pythonpandasdataframeapplyvalueerror

Create 2 or more columns from function's output in pandas


I'm trying to create two columns for a data frame from a function that returns a tuple I have an existing dataframe named df and I'm using apply lambda to calulate 2 values based upon 2 columns of my data frame

def f(a,b):
    return a+b, a-b
df['SUM'], df['DIFF'] = apply(lambda x: f(x.COLUMN_1,x.COLUMN_2)

but I'm getting the error:

ValueError: too many values to unpack (expected 2)

My function returns a series of tuples whith the same number of rows as df


Solution

  • Try the following:

    import pandas as pd
    
    df = pd.DataFrame({'a': [0,1,2], 'b': [3,4,5]})
    
    df[['SUM','DIFF']] = df[['a','b']].apply(lambda x: pd.Series({'SUM': x['a']+x['b'], 'DIFF': x['a']-x['b']}), axis=1)
    

    Yields:

       a  b  SUM  DIFF
    0  0  3    3    -3
    1  1  4    5    -3
    2  2  5    7    -3