Stephenie Liu Stephenie Liu - 23 days ago 9
Python Question

pandas resample irregular spaced time data

x1 x1.resample('1T').mean
ts

2017-09-09 17:22:42 7.0 NaN
2017-09-09 17:22:53 11.0 NaN
2017-09-09 17:23:04 9.0 NaN
2017-09-09 17:23:15 15.0 NaN
2017-09-09 17:23:26 13.0 NaN
2017-09-09 17:23:38 19.0 NaN
2017-09-09 17:23:49 13.0 NaN
2017-09-09 17:24:00 15.0 10.666667


the above is the result of
df.x1Avg = df.x1.resample('1T').mean()
the code only return result when the ts end in hh:mm:00. The result I want is

x1 x1.resample('1T').mean
ts

2017-09-09 17:22:42 7.0 (7+11)/2
2017-09-09 17:22:53 11.0 (7+11)/2
2017-09-09 17:23:04 9.0 (9+15+13+19+13)/5
2017-09-09 17:23:15 15.0 (9+15+13+19+13)/5
2017-09-09 17:23:26 13.0 (9+15+13+19+13)/5
2017-09-09 17:23:38 19.0 (9+15+13+19+13)/5
2017-09-09 17:23:49 13.0 (9+15+13+19+13)/5
2017-09-09 17:24:00 15.0 15

Answer Source

You can use transform

df.index = pd.to_datetime(df.index)
df['mean'] = df.resample('1T').transform('mean')

You get

                     x1     mean
ts      
2017-09-09 17:22:42 7.0     9.0
2017-09-09 17:22:53 11.0    9.0
2017-09-09 17:23:04 9.0     13.8
2017-09-09 17:23:15 15.0    13.8
2017-09-09 17:23:26 13.0    13.8
2017-09-09 17:23:38 19.0    13.8
2017-09-09 17:23:49 13.0    13.8
2017-09-09 17:24:00 15.0    15.0