[英]If else statement not working in custom python function
Below is a minimum reproducible example of what I'm trying to achieve with my custom function.下面是我试图用我的自定义 function 实现的最小可重复示例。 The function works if I remove the if statement and second argument.
如果我删除 if 语句和第二个参数,function 就可以工作。 I know the error is derived from the if statement, but I can't seem to figure out what the solution is.
我知道错误来自 if 语句,但我似乎无法弄清楚解决方案是什么。
df = pd.DataFrame({"odds":[100, -200, -400], "favorite":[0, 1, 1]})
def odd_bin_group_fn(odds, favorite):
if (odds <= -200 and favorite == 1):
return('large_favorite')
else:
return('other')
df['odd_bin'] = odd_bin_group_fn(df["odds"], df["favorite"])
Just use anonymous function and apply()
method:只需使用匿名 function 和
apply()
方法:
df['odd_bin']=df.apply(lambda x:'large_favorite' if (x['odds']<=-200) & (x['favorite']==1) else 'other',1)
OR或者
You can also use numpy's where()
method:您还可以使用 numpy 的
where()
方法:
df['odd_bin']=np.where((df['odds']<=-200) & (df['favorite']==1),'large_favorite','other')
To apply function on rows, you can use apply()
with axis=1
.要在行上应用 function,可以使用
apply()
和axis=1
。
df['odd_bin'] = df.apply(lambda row: odd_bin_group_fn(row["odds"], row["favorite"]), axis=1)
print(df)
odds favorite odd_bin
0 100 0 other
1 -200 1 large_favorite
2 -400 1 large_favorite
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.