为了账号安全,请及时绑定邮箱和手机立即绑定

如何将函数应用于两列Pandas数据帧

如何将函数应用于两列Pandas数据帧

慕妹3146593 2019-07-31 14:50:33
如何将函数应用于两列Pandas数据帧假设我有一个df列'ID', 'col_1', 'col_2'。我定义了一个函数:f = lambda x, y : my_function_expression。现在我想应用fto df的两列'col_1', 'col_2'来逐元素地计算一个新列'col_3',有点像:df['col_3'] = df[['col_1','col_2']].apply(f)  # Pandas gives : TypeError: ('<lambda>() takes exactly 2 arguments (1 given)'怎么做 ?** 添加详细示例如下 ***import pandas as pddf = pd.DataFrame({'ID':['1','2','3'], 'col_1': [0,2,3], 'col_2':[1,4,5]})mylist = ['a','b','c','d','e','f']def get_sublist(sta,end):    return mylist[sta:end+1]#df['col_3'] = df[['col_1','col_2']].apply(get_sublist,axis=1)# expect above to output df as below   ID  col_1  col_2            col_30  1      0      1       ['a', 'b']1  2      2      4  ['c', 'd', 'e']2  3      3      5  ['d', 'e', 'f']
查看完整描述

3 回答

?
慕妹3242003

TA贡献1824条经验 获得超6个赞

这是一个使用apply数据帧的示例,我正在调用它axis = 1。


注意区别在于,不是尝试将两个值传递给函数f,而是重写函数以接受pandas Series对象,然后索引Series以获取所需的值。


In [49]: df

Out[49]: 

          0         1

0  1.000000  0.000000

1 -0.494375  0.570994

2  1.000000  0.000000

3  1.876360 -0.229738

4  1.000000  0.000000


In [50]: def f(x):    

   ....:  return x[0] + x[1]  

   ....:  


In [51]: df.apply(f, axis=1) #passes a Series object, row-wise

Out[51]: 

0    1.000000

1    0.076619

2    1.000000

3    1.646622

4    1.000000

根据您的使用情况,创建一个pandas group对象,然后apply在该组上使用有时会很有帮助。


查看完整回答
反对 回复 2019-07-31
?
千万里不及你

TA贡献1784条经验 获得超9个赞

一个简单的解决方案是

df['col_3'] = df[['col_1','col_2']].apply(lambda x: f(*x), axis=1)


查看完整回答
反对 回复 2019-07-31
?
梵蒂冈之花

TA贡献1900条经验 获得超5个赞

在熊猫中有一种干净,单行的方式:


df['col_3'] = df.apply(lambda x: f(x.col_1, x.col_2), axis=1)

这允许f是具有多个输入值的用户定义函数,并使用(安全)列名而不是(不安全)数字索引来访问列。


数据示例(基于原始问题):


import pandas as pd


df = pd.DataFrame({'ID':['1', '2', '3'], 'col_1': [0, 2, 3], 'col_2':[1, 4, 5]})

mylist = ['a', 'b', 'c', 'd', 'e', 'f']


def get_sublist(sta,end):

    return mylist[sta:end+1]


df['col_3'] = df.apply(lambda x: get_sublist(x.col_1, x.col_2), axis=1)

产量print(df):


  ID  col_1  col_2      col_3

0  1      0      1     [a, b]

1  2      2      4  [c, d, e]

2  3      3      5  [d, e, f]


查看完整回答
反对 回复 2019-07-31
  • 3 回答
  • 0 关注
  • 634 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信