Pandas lambda 多参数作为回报 [英] Pandas lambda multiple argument in return
本文介绍了Pandas lambda 多参数作为回报的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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)
错误:
第 11 行,在df['x'], df['y'], df['z'] = df['a'].apply(lambda x: ced(x)) ValueError: 没有足够的值来解包(预期 3,得到2)
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
我不知道这里有什么问题.
I don't know what is the problem here.
推荐答案
我建议更改返回Series
和新列子集的函数:
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
另一种解决方案是通过构造函数创建DataFrame
:
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
这篇关于Pandas lambda 多参数作为回报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文