如何根据相邻列中的值将 lambda 函数应用于特定列

How to apply lambda function to specific column based on the values in the adjacent column

我正在尝试将 lambda 函数应用于 pandas 数据框。我的问题是如何使用 if 语句根据 b 列中的值将 lambda 函数应用于 a 列。

A B C
2 5 7
4 5 9
6 7 9
df['B'].apply(lambda x: x+3 if x<(#the value in column C) else x)

您需要使用 axis=1 在数据帧上调用 apply ,而不是在 B 列上调用:

>>> df.apply(lambda x: x['B']+3 if x['B']<x['C'] else x['B'], axis=1)
0     8
1     8
2    10
dtype: int64

但是,更有效(更快)的方法是这样做:

>>> df['B'] + df['B'].lt(df['C']) * 3
0     8
1     8
2    10
dtype: int64