I have this data:
df = pd.DataFrame({'date': {0: '2012-03-02', 1: '2012-04-01', 2: '2012-04-12', 3: '2012-04-14', 4: '2012-04-21', 5: '2012-05-12', 6: '2012-06-23', 7: '2012-06-25', 8: '2012-06-26', 9: '2012-06-27'},
'type': {0: 'Holiday', 1: 'Other', 2: 'Event', 3: 'Holiday', 4: 'Event', 5: 'Holiday', 6: 'Other', 7: 'Holiday', 8: 'Holiday', 9: 'Event'},
'locale': {0: 'Local', 1: 'Regional', 2: 'National', 3: 'Local', 4: 'National', 5: 'National', 6: 'National', 7: 'Regional', 8: 'Regional', 9: 'Local'}})
And this function:
def preprocess(data_input):
data = data_input.copy()
conditions = [
(data['type'] == 'Holiday') & (data.locale == 'National'),
(data['type'] == 'Holiday') & (data.locale == 'Regional'),
(data['type'] == 'Holiday') & (data.locale == 'Local')
]
values = [3,2,1]
data.loc[:,'Holiday'] = np.select(conditions, values, default=0)
conditions = [
(data['type'] == 'Event') & (data.locale == 'National'),
(data['type'] == 'Event') & (data.locale == 'Regional'),
(data['type'] == 'Event') & (data.locale == 'Local')
]
values = [3,2,1]
data.loc[:,'Events'] = np.select(conditions, values, default=0)
return(data)
When I run this function over df I will get:
preprocess(df)
Which is the expected result. However, I'm wondering about efficiency and best practices. I feel that both conditions use too many lines of code and that they could be written more elegant and efficiently, but I can't figure out how. I tried with np.where() but I struggled when I found out I would have to filter the data frames in each argument.
Any suggestions?
