Consider this example
import pandas as pd
import numpy as np
df = pd.DataFrame({'var1' : [1,2,3,4],
'var2' : ['a','b','c','d']})
df
Out[100]:
var1 var2
0 1 a
1 2 b
2 3 c
3 4 d
I have a function that takes var1
as input and returns three values that I want to store into three different variables. The following seems to work correctly
def myfunc(var):
return [['small list'], var + 2, ['another list']]
df.var1.apply(lambda x: myfunc(x))
Out[101]:
0 [[small list], 3, [another list]]
1 [[small list], 4, [another list]]
2 [[small list], 5, [another list]]
3 [[small list], 6, [another list]]
Name: var1, dtype: object
However, when I try to create the corresponding variables I get an error
df[['my small list', 'my numeric', 'other list']] = df.var1.apply(lambda x: myfunc(x))
ValueError: Must have equal len keys and value when setting with an iterable
What do you think?
I used to use the great zip
solution in Return multiple columns from pandas apply() but with the current Pandas 1.2
this solution does not work anymore
Thanks!