【发布时间】:2017-12-27 06:59:31
【问题描述】:
基本上我有一些带有维度(时间、纬度、经度)的网格化气象数据。
- 我需要遍历每个 gridsquare 的每个时间序列,确定连续天数 (“事件”)当变量高于阈值并将其存储到 一个新变量(THdays)
- 然后我查看新变量并找到超过一定持续时间的事件(THevents)
目前我有一个超级杂乱无章(非矢量化)的迭代,非常感谢您对如何加快这一进程的建议。谢谢!
import numpy as np
import itertools as it
##### Parameters
lg = 2000 # length to initialise array (must be long to store large number of events)
rl = 180 # e.g latitude
cl = 360 # longitude
pcts = [95, 97, 99] # percentiles which are the thresholds that will be compared
dt = [1,2,3] #duration thresholds, i.e. consecutive values (days) above threshold
##### Data
data # this is the gridded data that is (time,lat,lon) , e.g. data = np.random.rand(1000,rl,cl)
# From this data calculate the percentiles at each gridsquare (lat/lon combination) which will act as our thresholds
histpcts = np.percentile(data, q=pcts, axis = 0)
##### Initialize arrays to store the results
THdays = np.ndarray((rl, cl, lg, len(pcts)), dtype='int16') #Array to store consecutive threshold timesteps
THevents = np.ndarray((rl,cl,lg,len(pcts),len(dt)),dtype='int16')
##### Start iteration to identify events
for p in range(len(pcts)): # for each threshold value
br = data>histpcts[p,:,:] # Make boolean array where data is bigger than threshold
# for every lat/lon combination
for r,c in it.product(range(rl),range(cl)):
if br[:,r,c].any()==True: # This is to skip timeseries with nans only and so the iteration is skipped. Important to keep this or something that ignores an array of nans
a = [ sum( 1 for _ in group ) for key, group in it.groupby( br[:,r,c] ) if key ] # Find the consecutive instances
tm = np.full(lg-len(a), np.nan) # create an array of nans to fill in the rest
# Assign to new array
THdays[r,c,0:len(a),p] = a # Consecutive Thresholds days
THdays[r,c,len(a):,p] = tm # Fill the rest of array
# Now cycle through and identify events
# (consecutive values) longer than a certain duration (dt)
for d in range(len(dt)):
b = THdays[r,c,THdays[r,c,:,p]>=dt[d],p]
THevents[r,c,0:len(b),p,d] = b
【问题讨论】:
-
从内到外工作。您有一个三重嵌套的 for 循环。只需将内部循环提取到一个函数中并弄清楚如何对其进行矢量化。与任何其他编程任务一样,将问题分解为可管理的部分。以下是我以前做过的一些类似的事情:stackoverflow.com/questions/17529342 和 stackoverflow.com/questions/36853770 和 stackoverflow.com/questions/26251997
-
@JohnZwinck 谢谢我看看
标签: python numpy vectorization