我有一个如下所示的数据框
if DURATION < 370, then df['PRICE_PER_YEAR'] = df['PRICE']/ df['DURATION'] * 365
else df['PRICE_PER_YEAR'] = df['PRICE']
根据上述数据,我想根据以下条件创建一个新列PRICE_PER_YEAR。
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
预期输出:
{{1}}
答案 0 :(得分:1)
df['PRICE_PER_YEAR'] = df.apply(lambda x : x['PRICE']/ x['DURATION'] * 365 if x['DURATION'] < 370
else x['PRICE'], axis = 1)
答案 1 :(得分:1)
使用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