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

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

问题描述

我想使用apply函数: -以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’ : 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天全站免登陆