使用 apply 向现有数据框添加 2 个新列 [英] Add 2 new columns to existing dataframe using apply

查看:32
本文介绍了使用 apply 向现有数据框添加 2 个新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用以下应用函数:- 以 2 列作为输入 - 基于函数输出两个新列.

I want to use the apply function that: - Takes 2 columns as inputs - Outputs two new columns based on a function.

这个 add_multiply 函数就是一个例子.

An example is with this add_multiply function.

#function with 2 column inputs and 2 outputs
def add_multiply (a,b):
  return (a+b, a*b )

#example dataframe
df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})

#this doesn't work
df[['add', 'multiply']] = df.apply(lambda x: add_multiply(x['col1'], x['col2']), axis=1)

理想结果:

col1  col2  add  multiply
1     3     4    3
2     4     6    8

推荐答案

您可以在apply中添加result_type='expand':

'expand' : 类似列表的结果将变成列.

‘expand’ : list-like results will be turned into columns.

df[['add', 'multiply']]=df.apply(lambda x: add_multiply(x['col1'], x['col2']),axis=1,
                             result_type='expand')

或者调用一个数据框构造函数:

Or call a dataframe constructor:

df[['add', 'multiply']]=pd.DataFrame(df.apply(lambda x: add_multiply(x['col1'], 
                                    x['col2']), axis=1).tolist())

<小时>

   col1  col2  add  multiply
0     1     3    4         3
1     2     4    6         8

这篇关于使用 apply 向现有数据框添加 2 个新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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