2

I have 8760 raster file for the precipitation in the netherlands on hourly base, from the first day of the year (01.01.2020) till the last hour of the year (31.12.20). What I have to do with these files is to calculated the daily precipitation, so I need to sum up every raster file for each day. I am not comfortable using the python console in QGIS (3.10.14).

The best thing would be having a for loop who goes throug the name of the file, and when the day changes, they start the loop again and therefore the sum. The file name are named as follow: m%%_d%%_t%% so for the 3 of march at 5 pm the file name would be m04_d03_t17 (month, day and time).

How would you create a for loop who gives as a result the sum of the previous raster?

Maybe also to save in a directory.

1 Answer 1

3

I can help you get started with listing all raster and grouping them by day:

import os, datetime
from collections import defaultdict as dd
rasterfolder = r'/home/bera/Desktop/test/'
rasterlist = dd(list)

for root, folder, files in os.walk(rasterfolder):
    for file in files:
        fullname = os.path.join(root, file)
        if file.endswith('.tif'):
            tempstring = '20'+file
            thedate = datetime.datetime.strptime(tempstring, "%ym%m_d%d_t%H.tif")
            rasterlist[thedate.strftime('%Y-%m-%d')].append(fullname)

#rasterlist is now a dictionary with each day as key, and a list of all rasters as value, for example:
    #{'2020-02-03': ['/home/bera/Desktop/test/m02_d03_t17.tif', '/home/bera/Desktop/test/m02_d03_t18.tif']
    #2020-04-03': ['/home/bera/Desktop/test/m04_d03_t17.tif', '/home/bera/Desktop/test/m04_d03_t18.tif']}
            
            

for date, raster_list in rasterlist.items():
    outraster = '/home/bera/Desktop/{}.tif'.format(date)
    arraylist = []
    for r in raster_list:
        ds = gdal.Open(r)
        myarray = np.array(ds.GetRasterBand(1).ReadAsArray())
        arraylist.append(myarray)
    daysum = sum(arraylist)
    
    #Save the daysum array as a raster
    #that code goes here...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.