Pandas computer hourly average and set in the middle of the interval

I want to calculate the hourly average for a time series of wind speed and direction, but I want to set the time to half an hour. Thus, the average value from 14:00 to 15:00 will be at 14:30. Right now, I can only seem to get it to the left or right of the interval. Here is what I have now:

ts_g=[item.replace(second=0, microsecond=0) for item in dates_g]
dg = {'ws': data_g.ws, 'wdir': data_g.wdir}
df_g = pandas.DataFrame(data=dg, index=ts_g, columns=['ws','wdir'])
grouped_g = df_g.groupby(pandas.TimeGrouper('H'))
hourly_ws_g = grouped_g['ws'].mean()
hourly_wdir_g = grouped_g['wdir'].mean()

The output for this looks like this:

2016-04-08 06:00:00+00:00     46.980000
2016-04-08 07:00:00+00:00     64.313333
2016-04-08 08:00:00+00:00     75.678333
2016-04-08 09:00:00+00:00    127.383333
2016-04-08 10:00:00+00:00    145.950000
2016-04-08 11:00:00+00:00    184.166667
....

but I would like it to be like:

2016-04-08 06:30:00+00:00     54.556
2016-04-08 07:30:00+00:00     78.001
....

Thank you for your help!

+4
source share
1 answer

So the easiest way is to reselect and then use linear interpolation:

In [21]: rng = pd.date_range('1/1/2011', periods=72, freq='H')

In [22]: ts = pd.Series(np.random.randn(len(rng)), index=rng)
    ...: 

In [23]: ts.head()
Out[23]: 
2011-01-01 00:00:00    0.796704
2011-01-01 01:00:00   -1.153179
2011-01-01 02:00:00   -1.919475
2011-01-01 03:00:00    0.082413
2011-01-01 04:00:00   -0.397434
Freq: H, dtype: float64

In [24]: ts2 = ts.resample('30T').interpolate()

In [25]: ts2.head()
Out[25]: 
2011-01-01 00:00:00    0.796704
2011-01-01 00:30:00   -0.178237
2011-01-01 01:00:00   -1.153179
2011-01-01 01:30:00   -1.536327
2011-01-01 02:00:00   -1.919475
Freq: 30T, dtype: float64

In [26]: 

I believe that this is what you need.

,

, , :

In [29]: ts.head()
Out[29]: 
2011-01-01 00:00:00    0
2011-01-01 01:00:00    1
2011-01-01 02:00:00    2
2011-01-01 03:00:00    3
2011-01-01 04:00:00    4
Freq: H, dtype: int64

In [30]: ts2 = ts.resample('30T').interpolate()

In [31]: ts2.head()
Out[31]: 
2011-01-01 00:00:00    0.0
2011-01-01 00:30:00    0.5
2011-01-01 01:00:00    1.0
2011-01-01 01:30:00    1.5
2011-01-01 02:00:00    2.0
Freq: 30T, dtype: float64
+2

Source: https://habr.com/ru/post/1659874/


All Articles