我想在lambda函数中使用if ... elif ... else将lambda函数应用于DataFrame列。
df和代码是smth。像:
df=pd.DataFrame({"one":[1,2,3,4,5],"two":[6,7,8,9,10]})
df["one"].apply(lambda x: x*10 if x<2 elif x<4 x**2 else x+10)
显然这种方式不起作用。
有没有办法申请,如果.... elif ....其他的lambda?
如何使用List Comprehension重新获得相同的结果?
感谢您的回复。
答案 0 :(得分:54)
Nest if .. else
s:
lambda x: x*10 if x<2 else (x**2 if x<4 else x+10)
答案 1 :(得分:11)
我不建议在这里使用apply
- 如果有更好的选择,应该避免使用。
例如,如果您在系列上执行以下操作:
if cond1:
exp1
elif cond2:
exp2
else:
exp3
这通常是np.where
或np.select
的良好用例。
np.where
强> 上面的if
else
链可以使用
np.where(cond1, exp1, np.where(cond2, exp2, ...))
np.where
允许嵌套。使用一级嵌套,您的问题可以通过
df['three'] = (
np.where(
df['one'] < 2,
df['one'] * 10,
np.where(df['one'] < 4, df['one'] ** 2, df['one'] + 10))
df
one two three
0 1 6 10
1 2 7 4
2 3 8 9
3 4 9 14
4 5 10 15
np.select
强> 允许灵活的语法并且易于扩展。它遵循形式,
np.select([cond1, cond2, ...], [exp1, exp2, ...])
或者,在这种情况下,
np.select([cond1, cond2], [exp1, exp2], default=exp3)
df['three'] = (
np.select(
condlist=[df['one'] < 2, df['one'] < 4],
choicelist=[df['one'] * 10, df['one'] ** 2],
default=df['one'] + 10))
df
one two three
0 1 6 10
1 2 7 4
2 3 8 9
3 4 9 14
4 5 10 15
and
/ or
代替if
/ else
与if-else
类似,需要lambda
:
df['three'] = df["one"].apply(
lambda x: (x < 2 and x * 10) or (x < 4 and x ** 2) or x + 10)
df
one two three
0 1 6 10
1 2 7 4
2 3 8 9
3 4 9 14
4 5 10 15
仍然的Loopy解决方案比apply
更快。
df['three'] = [x*10 if x<2 else (x**2 if x<4 else x+10) for x in df['one']]
# df['three'] = [
# (x < 2 and x * 10) or (x < 4 and x ** 2) or x + 10) for x in df['one']
# ]
df
one two three
0 1 6 10
1 2 7 4
2 3 8 9
3 4 9 14
4 5 10 15
答案 2 :(得分:1)
出于可读性考虑,我更喜欢编写一个函数,尤其是当您处理许多情况时。对于原始问题:
def parse_values(x):
if x < 2:
return x * 10
elif x < 4:
return x ** 2
else:
return x + 10
df['one'].apply(parse_values)