python apply 返回多列,Dataframe Apply方法返回多个元素(系列)

该博客讨论如何在Pandas DataFrame中通过apply函数同时添加多个新的列。通过定义一个返回多个值的函数,可以实现对DataFrame的行进行操作并创建多个新列。更新后的函数返回一个列表,然后使用`result_type='broadcast'`参数将结果分配给DataFrame的新列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import pandas as pd

Let's say I have a dataframe like so:

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

it looks like this:

a b

0 0 1

1 1 2

2 2 3

3 3 4

and a function that multiplies X by Y:

def XtimesY(x,y):

return x*y

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)

It works !

Now I want to add multiple series:

I have this function:

def divideAndMultiply(x,y):

return x/y, x*y

something like this ?:

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

It doesn't work !

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.

解决方案

UPDATE

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]

Then do this:

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

You shall get the desired result:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值