I want to convert a date time series to season, for example for months 3, 4, 5 I want to replace them with 2 (spring); for months 6, 7, 8 I want to replace them with 3 (summer) etc.
So, I have this series
JavaScript
x
11
11
1
id
2
1 2011-08-20
3
2 2011-08-23
4
3 2011-08-27
5
4 2011-09-01
6
5 2011-09-05
7
6 2011-09-06
8
7 2011-09-08
9
8 2011-09-09
10
Name: timestamp, dtype: datetime64[ns]
11
and this is the code I have been trying to use, but to no avail.
JavaScript
1
19
19
1
# Get seasons
2
spring = range(3, 5)
3
summer = range(6, 8)
4
fall = range(9, 11)
5
# winter = everything else
6
7
month = temp2.dt.month
8
season=[]
9
10
for _ in range(len(month)):
11
if any(x == spring for x in month):
12
season.append(2) # spring
13
elif any(x == summer for x in month):
14
season.append(3) # summer
15
elif any(x == fall for x in month):
16
season.append(4) # fall
17
else:
18
season.append(1) # winter
19
and
JavaScript
1
10
10
1
for _ in range(len(month)):
2
if month[_] == 3 or month[_] == 4 or month[_] == 5:
3
season.append(2) # spring
4
elif month[_] == 6 or month[_] == 7 or month[_] == 8:
5
season.append(3) # summer
6
elif month[_] == 9 or month[_] == 10 or month[_] == 11:
7
season.append(4) # fall
8
else:
9
season.append(1) # winter
10
Neither solution works, specifically in the first implementation I receive an error:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
While in the second is a large list with errors. Any ideas please? Thanks
Advertisement
Answer
You can use a simple mathematical formula to compress a month to a season, e.g.:
JavaScript
1
3
1
>>> [month%12 // 3 + 1 for month in range(1, 13)]
2
[1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 1]
3
So for your use-case using vector operations (credit @DSM):
JavaScript
1
11
11
1
>>> temp2.dt.month%12 // 3 + 1
2
1 3
3
2 3
4
3 3
5
4 4
6
5 4
7
6 4
8
7 4
9
8 4
10
Name: id, dtype: int64
11