Python: Datetime to season
It's, also, possible to use dictionary mapping.
Create a dictionary that maps a month to a season:
In [27]: seasons = [1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 1] In [28]: month_to_season = dict(zip(range(1,13), seasons)) In [29]: month_to_season Out[29]: {1: 1, 2: 1, 3: 2, 4: 2, 5: 2, 6: 3, 7: 3, 8: 3, 9: 4, 10: 4, 11: 4, 12: 1}
Use it to convert the months to seasons
In [30]: df.id.dt.month.map(month_to_season) Out[30]: 1 3 2 3 3 3 4 4 5 4 6 4 7 4 8 4 Name: id, dtype: int64
Performance: This is fairly fast
In [35]: %timeit df.id.dt.month.map(month_to_season)
1000 loops, best of 3: 422 µs per loop
You can use a simple mathematical formula to compress a month to a season, e.g.:
>>> [month%12 // 3 + 1 for month in range(1, 13)]
[1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 1]
So for your use-case using vector operations (credit @DSM):
>>> temp2.dt.month%12 // 3 + 1
1 3
2 3
3 3
4 4
5 4
6 4
7 4
8 4
Name: id, dtype: int64