python pandas- apply函数带有两个参数到列 [英] python pandas- apply function with two arguments to columns

查看:7476
本文介绍了python pandas- apply函数带有两个参数到列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你可以使用两个不同列中的值作为参数吗?



如果两列的值相同,我有一个返回1的函数范围。否则返回0:

  def segmentMatch(RealTime,ResponseTime):
如果RealTime = 566和ResponseTime< ; = 566:
matchVar = 1
elif 566< RealTime< = 1132和566< ResponseTime< = 1132:
matchVar = 1
elif 1132< RealTime< = 1698和1132< ResponseTime< = 1698:
matchVar = 1
else:
matchVar = 0
return matchVar

我希望第一个参数 RealTime 成为我的数据框中的一列,使得该函数将取值该列中的每一行。例如 RealTime df ['TimeCol'] ,第二个参数是df ['ResponseCol']`。我希望结果成为数据帧中的一个新列。我发现了几个 线程已经回答了类似的问题,但它看起来这些参数是变量,而不是数据帧中的值。



我尝试了以下操作,但没有起作用:

  df ['NewCol'] = df.apply(segmentMatch,args =(df ['TimeCol'],df ['ResponseCol']),axis = 1) 


解决方案

为什么不这样做? b
$ b

  df ['NewCol'] = df.apply(lambda x:segmentMatch(x ['TimeCol'],x ['ResponseCol'])轴= 1)

而不是像你的例子那样将列作为参数传递,我们现在只需将每行中的适当条目作为参数传递,并存储结果在'NewCol'


Can you make a python pandas function with values in two different columns as arguments?

I have a function that returns a 1 if two columns have values in the same range. otherwise it returns 0:

def segmentMatch(RealTime, ResponseTime):
    if RealTime <= 566 and ResponseTime <= 566:
        matchVar = 1
    elif 566 < RealTime <= 1132 and 566 < ResponseTime <= 1132:
        matchVar = 1
    elif 1132 < RealTime <= 1698 and 1132 < ResponseTime <= 1698:
        matchVar = 1
    else:
        matchVar = 0
    return matchVar

I want the first argument, RealTime, to be a column in my data frame, such that the function will take the value of each row in that column. e.g. RealTime is df['TimeCol'] and the second argument is df['ResponseCol']`. And I'd like the result to be a new column in the dataframe. I came across several threads that have answered a similar question, but it looks like those arguments were variables, not values in rows of the dataframe.

I tried the following but it didn't work:

df['NewCol'] = df.apply(segmentMatch, args=(df['TimeCol'], df['ResponseCol']), axis=1)

解决方案

Why not just do this?

df['NewCol'] = df.apply(lambda x: segmentMatch(x['TimeCol'], x['ResponseCol']), axis=1)

Rather than trying to pass the column as an argument as in your example, we now simply pass the appropriate entries in each row as argument, and store the result in 'NewCol'.

这篇关于python pandas- apply函数带有两个参数到列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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