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)
错误:
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)
这个东西适用于
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)
输出:
a b x y
0 1 2 2 11
1 10 20 3 12
我不知道这里出了什么问题。
最佳答案
我建议更改返回Series
和新列子集的函数:
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
另一种解决方案是通过构造函数创建DataFrame
:
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
关于python - Pandas lambda 多个参数返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51283361/