在多列 pandas 上应用 lambda 行 [英] applying lambda row on multiple columns pandas

查看:92
本文介绍了在多列 pandas 上应用 lambda 行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个示例数据框:

I am creating a sample dataframe:

tp = pd.DataFrame({'source':['a','s','f'], 
                   'target':['b','n','m'], 
                   'count':[0,8,4]})

并根据'target'列的条件创建一个'col'列>>与源相同,如果匹配条件,则为默认值,如下:

And creating a column 'col' based on condition of 'target' column >> same as source, if matching condition, else to a default, as below:

tp['col'] = tp.apply(lambda row:row['source'] if row['target'] in ['b','n'] else 'x')

但它向我抛出了这个错误:KeyError: ('target', 'occurred at index count')

But it's throwing me this error: KeyError: ('target', 'occurred at index count')

如何在不定义函数的情况下使其工作?

How can I make it work, without defining a function?

推荐答案

你需要使用 axis=1 来告诉 Pandas 你想对每一行应用一个函数.默认为 axis=0.

You need to use axis=1 to tell Pandas you want to apply a function to each row. The default is axis=0.

tp['col'] = tp.apply(lambda row: row['source'] if row['target'] in ['b', 'n'] else 'x',
                     axis=1)


但是,对于此特定任务,您应该使用矢量化操作.例如,使用 numpy.where:

tp['col'] = np.where(tp['target'].isin(['b', 'n']), tp['source'], 'x')

pd.Series.isin 返回一个布尔序列,它告诉 numpy.where 是选择第二个还是第三个参数.

pd.Series.isin returns a Boolean series which tells numpy.where whether to select the second or third argument.

这篇关于在多列 pandas 上应用 lambda 行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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