0

When executing the code below

import numpy as np
import pandas as pd

def somef(t,y,u):
# Some silly function but close enough to represent actual use case
    y=t+u+y
    g=1*u*t
    l,o=y[0],g[0]
    return l,o
data=np.array([4,6,1,3])

df=pd.DataFrame(dict(a=[1,2,3,4],b=[3,6,4,1]))
df[['ttt','uuu']]=df.apply(lambda x: somef(data,x['a'],x['b']), axis=1)

The compiler return an error

ValueError: Columns must be same length as key

May I know what is the issue?

Expected output

a   b   ttt uuu
1   3   8   12
2   6   12  24
3   4   11  16
4   1   9   4

1 Answer 1

1

Pandas apply have an argument result_type. Assigning the result_type equal to expand resolve the issue.

‘expand’ : list-like results will be turned into columns.

Such that,

df[['ttt','uuu']]=df.apply(lambda x: somef(data,x['a'],x['b']), axis=1,result_type="expand")

Return

   a  b  ttt  uuu
0  1  3    8   12
1  2  6   12   24
2  3  4   11   16
3  4  1    9    4

Interesting enough, setting the output column as df['ttt','uuu'] and the result_type as None (which is the default value)

df['ttt','uuu']=df.apply(lambda x: somef(data,x['a'],x['b']), axis=1)

Return

   a  b (ttt, uuu)
0  1  3    (8, 12)
1  2  6   (12, 24)
2  3  4   (11, 16)
3  4  1     (9, 4)
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.