How do I extract the 2 hour interval for a given time series in python?

Viewed 91

I'm currently analyzing some rainfall data from NetCDF files, and after extracting the data, I have produced a time series of the 1-hour maximum rainfall between the years 1979-2020:

import glob
import numpy as np
from netCDF4 import Dataset
import pandas as pd
import xarray as xr

all_years = []

for file in glob.glob('*.nc'):
    #print(file)
    data = Dataset(file, 'r')
    time = data.variables['time']
    year = time.units[11:16]
    all_years.append(year)
 
year_start = '01-01-1979'
year_end = '31-12-2021'
date_range = pd.date_range(start = str(year_start),
                           end = str(year_end), 
                           freq = 'H')

df = pd.DataFrame(0.0,columns = ['tp'], index = date_range)

lat_freetown = 8.4657
lon_freetown = 13.2317

all_years.sort()

for yr in range(1979,2021):
    data = Dataset('era5_year' + str(yr)+ '.nc', 'r')
    
    lat = data.variables['latitude'][:]
    lon = data.variables['longitude'][:]
    
    sq_diff_lat = (lat - lat_freetown)**2
    sq_diff_lon = (lon - lon_freetown)**2
    
    min_index_lat = sq_diff_lat.argmin()
    min_index_lon = sq_diff_lon.argmin()
    
    tp = data.variables['tp']
    
    start = str(yr) + '-01-01'
    end = str(yr) + '-12-31'
    d_range = pd.date_range(start = start, 
                            end = end, 
                            freq = 'H')
    
    for t_index in np.arange(0, len(d_range)):
        print('Recording the value for: ' + str(d_range[t_index])+str(tp[t_index, min_index_lat, min_index_lon]))
        df.loc[d_range[t_index]]['tp'] = tp[t_index, min_index_lat, min_index_lon]

    
daily = df.resample('D').max()`

Now from here, I need to analyze this series for the 2-hour duration. I thought I may be able to use the resample function again with '2H':

df.resample('2H').max()

But I need to analyze the data in such a way that it reads the data on a sliding scale, for example:

  1. Data from 1pm to 3pm
  2. Data from 2pm to 4pm
  3. Data from 3pm to 5pm ...... etc

If anyone knows of a way that I can analyze my time series in this way, in 2-hour intervals but also analyzing the times in between, then any help would be greatly appreciated!

1 Answers

Use the rolling method which takes in a window

df.rolling('2H').max()
Related