Reputation: 37
strong textI got an excel file with dates, starting from 2019 till 2021. And i wanted to apply certain rules like if sales was made between 04.05.2019 and 09.05.2019 then it's a promo number 1, etc. The output is here
desired outcome
Upvotes: 2
Views: 89
Reputation: 862691
Use Series.between
for mask and set new values by numpy.where
:
import numpy as np
df['date'] = pd.to_datetime(df['date'], dayfirst=True)
mask = df['date'].between('2019-05-04', '2019-05-09')
df['new'] = np.where(mask, 'promo number 1', 'no promo')
If there is multiple values, e.g. in dictionary:
d = {
'25% sales': ('2019-04-29','2019-04-30'),
'40% sales': ('2019-05-12','2019-05-15'),
'50% sales': ('2019-05-18','2019-05-22')
}
df['date'] = pd.to_datetime(df['date'], dayfirst=True)
for val, (date1, date2) in d.items():
mask = df['date'].between(date1, date2)
df.loc[mask, 'new'] = val
df['new'] = df['new'].fillna('no promo')
Upvotes: 1