将函数应用于以其他列作为参数的 Pandas 列 [英] Apply function to pandas column having other column as argument

查看:36
本文介绍了将函数应用于以其他列作为参数的 Pandas 列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我正在尝试使用 y 作为参数将函数应用于列 x,因此对于每一行我想应用 xy,类似这样:

Hey I am trying to apply a function to a column x using y as parameter, so for every row I want to apply x to y, something like this:

def fun(x, y):
    return x + y



df['xy'] = df['x'].apply(fun, args = df['y'])

但它不起作用.有任何想法吗?请注意,我真正的函数不是添加两个值那么简单

But it does not work. Any ideas? Note that my real function is not as simple as adding two values

推荐答案

使用 DataFrame.apply 带有 lambda 函数和 axis=1 用于处理每行:

Use DataFrame.apply with lambda function and axis=1 for procesing per rows:

df['xy'] = df.apply(lambda x: fun(x['x'], x['y']), axis=1)

但如果可能的话,最好使用矢量化操作,这里:

But if possible, better is use vectorized operations, here:

df['xy'] = df['x'] + df['y']

这篇关于将函数应用于以其他列作为参数的 Pandas 列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆