0

I have a dataframe where say, 1 column is filled with dates and the 2nd column is filled with Ages. I want to add a 3rd column which looks at the Ages column and multiplies it the value by 2 if the value in the row is < 20, else just put the Age in that row. The lambda function below multiples every Age by 2.


def fun(df):
    change = df.loc[:, "AGE"].apply(lambda x: x * 2 if x <20 else x)
    df.insert(2, "NEW_AGE", change)

    return df



1 Answers1

1

Use pandas.Series.where:

import pandas as pd
import numpy as np

df = pd.DataFrame(np.arange(15, 25), columns=['AGE'])
df['AGE'].where(df['AGE'] >= 20, df['AGE'] * 2)

Output:

0    30
1    32
2    34
3    36
4    38
5    20
6    21
7    22
8    23
9    24
Name: AGE, dtype: int64
Anton vBR
  • 18,287
  • 5
  • 40
  • 46
Chris
  • 29,127
  • 3
  • 28
  • 51