我需要访问一些grib文件。我已经知道如何使用pygrib来做这件事了。然而,我知道如何做到这一点的唯一方法是极其缓慢的。
我有34年的3hrly数据,它们被组织成每年约36个文件(大约每10天一个)。总共约1000个文件。
每个文件有大约80条“消息”( 10天内每天8个值)。(它们是空间数据,所以它们有(x,y)维)。
为了读取我的所有数据,我写道:
grbfile = pygrib.index(filename, 'shortName', 'typeOfLevel', 'level')
var1 = grbfile.select(typeOfLevel='pressureFromGroundLayer', level=180, shortName='unknown')
for it in np.arange(len(var1)):
var_values, lat1, lon1 = var1[it].data()
if (it==0):
tot_var = np.expand_dims(var_values,axis=0)
else:
tot_var = np.append(tot_var, np.expand_dims(var_values,axis=0),axis=0)并对1000个文件中的每个文件重复此操作。
有没有更快的方法?比如一次加载每个grib文件的大约80个图层?类似于:
var_values, lat1, lon1 = var1[:].data()发布于 2016-11-15 01:10:14
如果我理解正确的话,您希望将每个文件中所有80条消息的数据堆叠到一个数组中。
我必须警告你,该数组将变得非常大,并可能导致NumPy根据网格大小等抛出MemoryError (我以前也遇到过这种情况)。
也就是说,你可以这样做:
# substitute with a list of your file names
# glob is a builtin library that can help accomplish this
files = list_of_files
grib = pygrib.open(files[0]) # start with the first one
# grib message numbering starts at 1
data, lats, lons = grib.message(1).data()
# while np.expand_dims works, the following is shorter
# syntax wise and will accomplish the same thing
data = data[None,...] # add an empty dimension as axis 0
for m in xrange(2, grib.messages + 1):
data = np.vstack((data, grib.message(m).values[None,...]))
grib.close() # good practice
# now data has all the values from each message in the first file stacked up
# time to stack the rest on there
for file_ in files[1:]: # all except the first file which we've done
grib = pygrib.open(file_)
for msg in grib:
data = np.vstack((data, msg.values[None,...]))
grib.close()
print data.shape # should be (80 * len(files), nlats, nlons)这可能会给你带来一些速度。pygrib.open对象的作用类似于生成器,因此它们在调用时向您传递每个pygrib.gribmessage对象,而不是像pygrib.index的select()方法那样构建它们的列表。如果你需要一个特定文件中的所有消息,那么这就是我访问它们的方式。
希望它能帮上忙!
https://stackoverflow.com/questions/39778290
复制相似问题