如何在 pandas 中使用多列映射功能? [英] How to map a function using multiple columns in pandas?

查看:180
本文介绍了如何在 pandas 中使用多列映射功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经签出了map,apply,mapapply和Combine,但是似乎找不到一种简单的方法来进行以下操作:

I've checked out map, apply, mapapply, and combine, but can't seem to find a simple way of doing the following:

我有一个包含10列的数据框.我需要将它们中的三个传递给带有标量并返回标量的函数...

I have a dataframe with 10 columns. I need to pass three of them into a function that takes scalars and returns a scalar ...

some_func(int a, int b, int c) returns int d

我要应用此方法,并在数据框中创建一个包含结果的新列.

I want to apply this and create a new column in the dataframe with the result.

df['d'] = some_func(a = df['a'], b = df['b'], c = df['c'])

我发现的所有解决方案似乎都建议重写some_func以使用Series而不是标量,但这是不可能的,因为它是另一个软件包的一部分.我该如何优雅地做到以上几点?

All the solutions that I've found seem to suggest to rewrite some_func to work with Series instead of scalars, but this is not possible as it is part of another package. How do I elegantly do the above?

推荐答案

使用 pd.DataFrame.apply() ,如下所示:

Use pd.DataFrame.apply(), as below:

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

注意:当 @ashishsingal 询问列时,应为axis参数提供值1,默认值为0(如文档,然后复制到下面).

NOTE: As @ashishsingal asked about columns, the axis argument should be provided with a value of 1, as the default is 0 (as in the documentation and copied below).

轴:{0或索引",1或列"},默认为0

axis : {0 or ‘index’, 1 or ‘columns’}, default 0

  • 0或索引":将功能应用于每列
  • 或列":将函数应用于每一行

这篇关于如何在 pandas 中使用多列映射功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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