简体   繁体   中英

Creating a Rolling Mean with a Changing Window on Pandas

I have a Pandas dataframe as shown below. I am looking to creating a 7 day rolling mean for the temperature. I understand how to do this if it was one reading per day ( dataset['rolling_temp'] = dataset.iloc[:,3].rolling(window=7).mean() ) but the problem involves having a random number of readings per day. ie 1 day may be multiple rows.
Any help would be much appreciated!

    day   temperature 
1     1          18.0           
2     1          19.0
3     2          18.0
4     3          17.0
5     4          18.5 
6     4          19.0
7     5          18.0
8     6          19.0
9     7          18.5
10    8          17.5
11    9          17.0
12   10          18.0
13   11          19.0
14   12          19.5
15   13          16.5
16   13          17.0

How about doing a .groupby first and then doing .rolling ? That solves the problem of having multiple days and gives you one value per day.

dataset = dataset.groupby('day')['temperature'].mean().reset_index().iloc[:,3].rolling(window=7).mean()

You should be able to produce rolling stats if you convert your days into proper dates and make the index out of them. You will have to include months and years, so add extra columns if you do not store such values already, and then:

dataset['date'] = dataset[['year', 'month', 'day']].apply(lambda row: '{}-{}-{}'.format(row['year'], row['month'], row['day']), axis=1)
dataset.set_index('date', inplace=True')
dataset.temperature.rolling('7D', min_periods=1).mean()

See for your reference at the bottom of this page . You can also try to resample the index:

dataset.temperature.resample('D').rolling('7D', min_periods=1).mean()

Note that this may not work with older versions of pandas, so if you run into errors consider upgrading to the latest stable.

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