Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading