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

Time:01-30

I am trying a apply a lambda function to a pandas data frame. My question is how can I apply a lambda function to column a based on value in column b using if statement.

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)

CodePudding user response:

You need to call apply on the dataframe, with axis=1, instead of on the B column:

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

But, a much more efficient (faster) way would be to do this:

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