Pandas lambda multiple argument in return

2019-08-09 00:23发布

import pandas as pd
import numpy as np

def ced(x):
    return x+1, x+2, x+3


df = pd.DataFrame(data=[[1,2],[10,20]], columns=['a','b'])


df['x'], df['y'], df['z'] = df['a'].apply(lambda x: ced(x)) 


print(df)

error:

line 11, in df['x'], df['y'], df['z'] = df['a'].apply(lambda x: ced(x)) ValueError: not enough values to unpack (expected 3, got 2)

this thing works for

import pandas as pd
import numpy as np

def ced(x):
    return x+1, x+2


df = pd.DataFrame(data=[[1,2],[10,20]], columns=['a','b'])


df['x'], df['y'] = df['a'].apply(lambda x: ced(x)) 


print(df)

output:

    a   b  x   y
0   1   2  2  11
1  10  20  3  12

I don't know what is the problem here.

1条回答
不美不萌又怎样
2楼-- · 2019-08-09 01:02

I suggest change function for return Series and subset of new columns:

def ced(x):
    return pd.Series([x+1, x+2, x+2])

df = pd.DataFrame(data=[[1,2],[10,20]], columns=['a','b'])


df[['x','y', 'z']] = df['a'].apply(lambda x: ced(x)) 

print(df)
    a   b   x   y   z
0   1   2   2   3   3
1  10  20  11  12  12

Another solution is create DataFrame by constructor:

def ced(x):
    return x+1, x+2, x+2

df = pd.DataFrame(data=[[1,2],[10,20]], columns=['a','b'])


df[['x','y', 'z']] = pd.DataFrame(df['a'].apply(lambda x: ced(x)).values.tolist())
print(df)
    a   b   x   y   z
0   1   2   2   3   3
1  10  20  11  12  12
查看更多
登录 后发表回答