你能用两个不同列中的值作为参数创建一个 pandas 函数吗?
我有一个函数,如果两列的值在同一范围内,则返回 1。否则返回 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
我想要第一个论点,RealTime
,成为我的数据框中的一列,这样该函数将采用该列中每一行的值。例如RealTime
is df['TimeCol']
第二个参数是df['ResponseCol']
。我希望结果成为数据框中的一个新列。我碰到several https://stackoverflow.com/questions/30822535/apply-function-to-column-in-pandas-dataframe-that-takes-two-arguments threads https://stackoverflow.com/questions/12182744/python-pandas-apply-a-function-with-arguments-to-a-series已经回答了类似的问题,但看起来这些参数是变量,而不是数据帧行中的值。
我尝试了以下方法,但没有成功:
df['NewCol'] = df.apply(segmentMatch, args=(df['TimeCol'], df['ResponseCol']), axis=1)
为什么不直接这样做呢?
df['NewCol'] = df.apply(lambda x: segmentMatch(x['TimeCol'], x['ResponseCol']),
axis=1)
我们现在只需将每行中的适当条目作为参数传递,并将结果存储在中,而不是像示例中那样尝试将列作为参数传递'NewCol'
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)