简体   繁体   中英

How can I use the isel method from xarray to select a range of dates?

I'm working on subsetting NASA DAYMET data based on a range of dates - specifically, I'm trying to automate the subsetting of 20 years worth of daily climate data, but am only interested in the summer months of each year. I've managed to get my code to partially work but it is still having trouble with updating for each year. ie if four years of data are specified, the same year's worth of daily data is output four different times, with only the year in the title of the plot updated. The resulting plots have updated years in the title but the data itself is only from one year.

The loop currently outputs each day from the summer months (June-August), but the output data is not updating the year correctly. I have been working with isel function from xarray as it has an add-on that adds the ability to work with raster data.

I'm inclined to believe that the issue resides with this line in the second nested loop:
prcp_1day_export = prcp_clip.isel(time=spec_day)

The end result of the code should be a matplotlib plot and a.tif file with the original data that has been clipped to my study area.

for spec_year in range(2000, 2003):
        print("year = " + str(spec_year))
        start_date = dt.datetime(spec_year, 6, 1) # specify your own start date
        end_date = dt.datetime(spec_year, 7, 1)  # specify your end start date
        beg_day = (start_date - dt.datetime(spec_year, 1, 1)).days
        end_day = beg_day + 92 
        print(start_date)
        print(end_date)
        print(beg_day)
        print(end_day)
        
        for spec_day in range(beg_day, end_day):
            # rename and export
#             print(str(spec_day)) #spec_day will be the value to use to specify what time equals a particular day
            # The line below is the likely result of the inaccurate specification of year when automating the subset.
            prcp_1day_export = prcp_clip.isel(time=spec_day)
            print(str(prcp_1day_export))
            prcp_1day_export.rio.to_raster("prcp_1day_export" + "_" + str(spec_day) + "_" + str(spec_year) + ".tif")
            fig, ax = plt.subplots(figsize = (20,10))
            prcp_1day_export.plot(ax=ax, robust=True, cbar_kwargs={'label': 'mm/day'})
            ga_shape_lcc.plot(ax = ax, color = 'none', edgecolor = 'red')
            fig.savefig("prcp_1day_export" + "_" + str(spec_day) + "_" + str(spec_year) + ".png")
            

print("Finished")

Any thoughts on how to approach the issue are highly appreciated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM