使用函数 return 来自特定列输入的多列输出使用 Pandas

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 结果:

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

你的函数将 return one 系列与 NAs 或当 my_funct 匹配时与二元组。

解决它的一种方法是改为 return 系列,它将通过应用自动扩展:

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

当您尝试将数据框解包为元组时,它 returns 列标签。这就是为什么你得到 (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