python lambda if elif_Lambda包括if…elif…els

我不建议在这里使用apply:如果有更好的替代品,就应该避免使用。

例如,如果要对序列执行以下操作:if cond1:

exp1

elif cond2:

exp2

else:

exp3

这通常是np.where或np.select的一个很好的用例。

numpy.where

上面的ifelse链可以使用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

numpy.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

列表理解

循环解决方案仍然比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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值