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
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.