如何使用 pandas 在 5 天 window 中计算每个观察计数的平均评分?
How do I calculate a mean rating per observations counts in a 5 day window using pandas?
我正在尝试为我使用 Python Pandas DataFrame 为不同日期所做的评分设置 5 天(可调整)运行 均值。
我可以使用以下代码轻松获得日均平均值
import pandas as pd
import datetime as dt
RTC = pd.read_csv(...loads file, has 'Date' and 'Rating' columns...)
daterange = RTC['Date'].max() - RTC['Date'].min()
days_means = []
for day_offset in range(daterange.days+1):
filldate = (RTC['Date'].min() + dt.timedelta).strftime('%Y-%m-%d')
days_means.append(RTC[RTC['Date']==filldate]['Rating'].mean())
我认为最自然的扩展方法是将 filldate 设为列表(或系列?),然后使用新掩码
RTC['Date'] in filldate
但是如果我这样做,我会收到一条错误消息
ValueError: The truth value of a Series is ambiguous. Use a.empty,
a.bool(), a.item(), a.any() or a.all().
我想我想在其中的某处放置一个任意语句,但我无法让它工作。
有没有人对如何使其正常工作有建议?
谢谢!
编辑:
作为参考,这是我的数据的样子
Date Rating OtherColumns...
1-1-2014 5 ...
1-2-2014 6
1-2-2014 7
1-3-2014 8
1-3-2014 2
1-4-2014 3
1-6-2014 6
...
因此 1-3-2014 的 5 天平均值为 (5+6+7+8+2+3)/6。请注意,1-2-2014 和 1-3-2014 有两个条目,1-5-2014 没有。
根据新信息更新答案:
#set up new example frame
rng = pd.DatetimeIndex(pd.to_datetime(['1/1/2014','1/2/2014','1/2/2014', '1/3/2014', '1/3/2014','1/4/2014','1/6/2014']))
df = pd.DataFrame({'rating':[5,6,7,8,2,3,6],'date':rng})
#set date as datetime index
df.set_index('date',inplace=True)
正在计算 5 天的中心平均值。因为数据框可能有缺失的天数或有超过 1 个观测值的天数,所以数据需要以天数的频率重新采样,空白天数填充为 0:
pd.rolling_mean(df.resample('1D',how='sum').fillna(0),5, min_periods=1, center=True)
这个returns:
2014-01-01 9.333333
2014-01-02 7.750000
2014-01-03 6.200000
2014-01-04 6.400000
2014-01-05 4.750000
2014-01-06 3.000000
请注意 2014-01-03 的 5 天移动平均线是 31/5 而不是 31/6
添加一个解决方案,使用以 5 天为中心 window 而非五天滚动平均值的观察次数给出平均值。
#create timedeltas for window
forward =pd.Timedelta('2 days')
back = pd.Timedelta('-2 days')
def f(x):
five_day_obs = df.rating[(df.date >= x + back) & (df.date < x+ forward)]
return five_day_obs.sum().astype(float)/five_day_obs.count()
这个returns:
df.date.apply(f)
0 6.000000
1 5.600000
2 5.600000
3 5.166667
4 5.166667
5 5.200000
6 4.500000
Name: date, dtype: int64
我正在尝试为我使用 Python Pandas DataFrame 为不同日期所做的评分设置 5 天(可调整)运行 均值。
我可以使用以下代码轻松获得日均平均值
import pandas as pd
import datetime as dt
RTC = pd.read_csv(...loads file, has 'Date' and 'Rating' columns...)
daterange = RTC['Date'].max() - RTC['Date'].min()
days_means = []
for day_offset in range(daterange.days+1):
filldate = (RTC['Date'].min() + dt.timedelta).strftime('%Y-%m-%d')
days_means.append(RTC[RTC['Date']==filldate]['Rating'].mean())
我认为最自然的扩展方法是将 filldate 设为列表(或系列?),然后使用新掩码
RTC['Date'] in filldate
但是如果我这样做,我会收到一条错误消息
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
我想我想在其中的某处放置一个任意语句,但我无法让它工作。
有没有人对如何使其正常工作有建议?
谢谢!
编辑: 作为参考,这是我的数据的样子
Date Rating OtherColumns...
1-1-2014 5 ...
1-2-2014 6
1-2-2014 7
1-3-2014 8
1-3-2014 2
1-4-2014 3
1-6-2014 6
...
因此 1-3-2014 的 5 天平均值为 (5+6+7+8+2+3)/6。请注意,1-2-2014 和 1-3-2014 有两个条目,1-5-2014 没有。
根据新信息更新答案:
#set up new example frame
rng = pd.DatetimeIndex(pd.to_datetime(['1/1/2014','1/2/2014','1/2/2014', '1/3/2014', '1/3/2014','1/4/2014','1/6/2014']))
df = pd.DataFrame({'rating':[5,6,7,8,2,3,6],'date':rng})
#set date as datetime index
df.set_index('date',inplace=True)
正在计算 5 天的中心平均值。因为数据框可能有缺失的天数或有超过 1 个观测值的天数,所以数据需要以天数的频率重新采样,空白天数填充为 0:
pd.rolling_mean(df.resample('1D',how='sum').fillna(0),5, min_periods=1, center=True)
这个returns:
2014-01-01 9.333333
2014-01-02 7.750000
2014-01-03 6.200000
2014-01-04 6.400000
2014-01-05 4.750000
2014-01-06 3.000000
请注意 2014-01-03 的 5 天移动平均线是 31/5 而不是 31/6
添加一个解决方案,使用以 5 天为中心 window 而非五天滚动平均值的观察次数给出平均值。
#create timedeltas for window
forward =pd.Timedelta('2 days')
back = pd.Timedelta('-2 days')
def f(x):
five_day_obs = df.rating[(df.date >= x + back) & (df.date < x+ forward)]
return five_day_obs.sum().astype(float)/five_day_obs.count()
这个returns:
df.date.apply(f)
0 6.000000
1 5.600000
2 5.600000
3 5.166667
4 5.166667
5 5.200000
6 4.500000
Name: date, dtype: int64