ValueError: too many values to unpack when using apply to return multiple values

Advertisements

I am using apply function to return 2 new columns, and then I got an error, not sure what is wrong? Thanks for your help.

def calc_test(row):

    a=row['col1']+row['col2']
    b=row['col1']/row['col2']

    return (a,b)

df_test_dict={'col1':[1,2,3,4,5],'col2':[10,20,30,40,50]}
df_test=pd.DataFrame(df_test_dict)
df_test

    col1    col2
0   1   10
1   2   20
2   3   30
3   4   40
4   5   50
df_test['a'],df_test['b']=df_test.apply(lambda row:calc_test(row),axis=1)
df_test

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
C:\Temp\1/ipykernel_12160/3210544870.py in <module>
      2 df_test=pd.DataFrame(df_test_dict)
      3 
----> 4 df_test['a'],df_test['b']=df_test.apply(lambda row:calc_test(row),axis=1)
      5 df_test

ValueError: too many values to unpack (expected 2)

>Solution :

apply doesn’t return two new columns, it returns one series (column) with cells being a tuple. You can try:

df_test[['a','b']] = pd.DataFrame(df_test.apply(lambda row:calc_test(row),axis=1).tolist())

Leave a ReplyCancel reply