我不建议在这里使用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