Dataframe Apply方法返回多个元素(系列) [英] Dataframe Apply method to return multiple elements (series)

查看:1392
本文介绍了Dataframe Apply方法返回多个元素(系列)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import pandas as pd

假设我有一个dataframe像这样:

df = pd.DataFrame({"a":range(4),"b":range(1,5)})

它看起来像这样:

   a  b
0  0  1
1  1  2
2  2  3
3  3  4

和一个将X乘以Y的函数:

and a function that multiplies X by Y:

def XtimesY(x,y):
    return x*y

如果我想向df添加新的熊猫系列,我可以这样做:

If I want to add a new pandas series to df I can do:

df["c"] =df.apply( lambda x:XtimesY(x["a"],2), axis =1)

它有效!

现在我要添加多个系列:

Now I want to add multiple series:

我有这个功能:

def divideAndMultiply(x,y):
    return x/y, x*y

类似这样的东西?:

df["e"], df["f"] = df.apply( lambda x: divideAndMultiply(x["a"],2) , axis =1)

它不起作用!

我希望'e'列接受除法,而'f'列接受乘法!

I want the 'e' column to receive the divisions and 'f' column the multiplications !

注意:这不是我正在使用的代码,但是我期望相同的行为.

Note: This is not the code I'm using but I'm expecting the same behavior.

推荐答案

更新

已针对版本0.23更新-使用result_type='broadcast'以获得更多详细信息,请参考文档

Updated for version 0.23 - using result_type='broadcast' for further details refer to documentation

像这样重新定义您的功能:

Redefine your function like this:

def divideAndMultiply(x,y):
    return [x/y, x*y]

然后执行以下操作:

df[['e','f']] = df.apply(lambda x: divideAndMultiply(x["a"], 2), axis=1, result_type='broadcast')

您将获得期望的结果:

In [118]: df
Out[118]:
   a  b  e  f
0  0  1  0  0
1  1  2  0  2
2  2  3  1  4
3  3  4  1  6

这篇关于Dataframe Apply方法返回多个元素(系列)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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