Reputation: 2871
I have a data frame as shown below
ID PRICE DURATION
1 10 30
2 200 730
3 40 60
4 300 400
5 100 180
From the above data, I would like to create a new column PRICE_PER_YEAR based on below condition.
if DURATION < 370, then df['PRICE_PER_YEAR'] = df['PRICE']/ df['DURATION'] * 365
else df['PRICE_PER_YEAR'] = df['PRICE']
Expected Output:
ID PRICE DURATION PRICE_PER_YEAR
1 10 30 121.66
2 200 730 200
3 40 60 243.33
4 300 400 300
5 100 180 202.77
Upvotes: 0
Views: 34
Reputation: 7723
Use np.where
>>> df['PRICE_PER_YEAR'] = np.where(df.DURATION < 370, df['PRICE']/ df['DURATION']*365, df['PRICE'])
>>> df
ID PRICE DURATION PRICE_PER_YEAR
0 1 10 30 121.666667
1 2 200 730 200.000000
2 3 40 60 243.333333
3 4 300 400 300.000000
4 5 100 180 202.777778
Upvotes: 1
Reputation: 159
df['PRICE_PER_YEAR'] = df.apply(lambda x : x['PRICE']/ x['DURATION'] * 365 if x['DURATION'] < 370
else x['PRICE'], axis = 1)
Upvotes: 1