繁体   English   中英

使用函数从使用熊猫的特定列输入返回多列输出

[英]Use a function to return multiple column outputs from specific column inputs using Pandas

我想通过应用从多个特定的现有列中获取输入的函数,将两个新列添加到我的数据框中。

这是我的方法,可用于返回一列,但不能返回多列:

这是我的DataFrame:

d = {'a': [3,0,2,2],
    'b': [0,1,2,3],
    'c': [1,1,2,3],
    'd': [2,2,1,3]}

df = pd.DataFrame(d)

我正在尝试应用此功能:

def myfunc(a,b,c):
    if a > 2 and b > 2:
        print('condition 1',a,b)
        return pd.Series((a,b))
    elif a < 2 and c < 2:
        print('condition 2',a,c)
        return pd.Series((b,c))
    else:
        print('no condition')
        return pd.Series((None,None))

像这样:

df['e'],df['f'] = df.apply(lambda x: myfunc(x['a'],x['b'],x['c']),axis=1)

输出:

no condition
no condition
condition 2 0 1
no condition
no condition

DataFrame结果:

在此处输入图片说明

如何输入多列并取出多列?

当my_funct匹配时,您的函数将使用NAs或2元组返回一个系列。

解决它的一种方法是返回Series,该序列将通过apply自动扩展:

def myfunc(col1,col2,col3):
    if col1 == 'x' and col2 == 'y':
        return pd.Series((col1,col2))
    if col2 == 'a' and col3 == 'b':
        return pd.Series(('yes','no'))

请注意使用双括号将一个参数作为元组传递。 列表也可以。

问题在于分配,而不是myfunc

当您尝试将数据框解压缩为元组时,它将返回列标签。 这就是为什么您得到所有​​东西的(0,1)

df['e'], df['f'] = pd.DataFrame([[8, 9]] * 1000000, columns=['Told', 'You'])
print(df)

   a  b  c  d     e    f
0  3  0  1  2  Told  You
1  0  1  1  2  Told  You
2  2  2  2  1  Told  You
3  2  3  3  3  Told  You

使用join

df.join(df.apply(lambda x: myfunc(x['a'],x['b'],x['c']),axis=1))

pd.concat

pd.concat([df, df.apply(lambda x: myfunc(x['a'],x['b'],x['c']),axis=1)], axis=1)

都给

   a  b  c  d    e    f
0  3  0  1  2  NaN  NaN
1  0  1  1  2  1.0  1.0
2  2  2  2  1  NaN  NaN
3  2  3  3  3  NaN  NaN

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM