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.

PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Oct 20, 2021 at 16:47

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...
answered Oct 20, 2021 at 17:41

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.