Skip to content

Commit bdcd626

Browse files
EliEli
authored andcommitted
Accelerate apply_climatology.
1 parent 33577b7 commit bdcd626

1 file changed

Lines changed: 8 additions & 11 deletions

File tree

vtools/functions/climatology.py

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,7 @@ def apply_climatology(climate, index):
147147
-------
148148
DataFrame or Series as given by climate with values extracted from climatology for the month or day
149149
"""
150-
import numpy as np
150+
151151

152152
if len(climate) not in [12, 365, 366]:
153153
raise ValueError("Length of climatology must be 12,365 or 366")
@@ -156,17 +156,14 @@ def apply_climatology(climate, index):
156156

157157
freq = "month" if len(climate) == 12 else "day"
158158

159-
df = pd.DataFrame(index=index, data=np.zeros(len(index), dtype="d"))
160-
161-
def rowFunc1(row):
162-
return climate.loc[row.name.dayofyear, :]
163-
164-
def rowFunc2(row):
165-
return climate.loc[row.name.month, :]
166-
159+
# Vectorized lookup
167160
if freq == "day":
168-
out = df.apply(rowFunc1, axis=1)
161+
dayofyear = index.dayofyear
162+
# Ensure day 366 is handled
163+
dayofyear = np.where(dayofyear > 365, 366, dayofyear)
164+
out = climate.loc[dayofyear].set_index(index)
169165
else:
170-
out = df.apply(rowFunc2, axis=1)
166+
month = index.month
167+
out = climate.loc[month].set_index(index)
171168

172169
return out

0 commit comments

Comments
 (0)