我有一个时间序列,在该序列中,客户在某一天花费了一定价值的现金。我被要求逐月找出在2018年1月至2018年12月的12个月之间有多少个唯一客户。
我正在努力找出如何使用rolling()函数设置一个12个月的窗口以计算此数字。有人可以帮忙吗?
date value customers
2018-01-01 5.0 a
2018-01-01 10.0 a
2018-01-02 2.0 c
2018-01-04 10.0 b
2018-01-06 20.0 a
答案 0 :(得分:1)
IIUC,您只需要在索引周期内使用groupby。我在样本中为不同的月份和年份添加了几行
示例df
value customers
date
2018-01-01 5.0 a
2018-01-01 10.0 a
2018-01-02 2.0 c
2018-01-04 10.0 b
2018-01-06 20.0 a
2018-02-12 5.0 a
2018-02-12 2.0 c
2018-02-14 10.0 b
2018-02-16 20.0 a
2019-01-01 5.0 a
2019-01-01 10.0 a
2019-01-02 2.0 c
2019-01-06 20.0 a
2019-02-12 5.0 a
2019-02-12 2.0 c
2019-02-14 10.0 b
2018-02-16 20.0 a
df.groupby(df.index.to_period('M')).customers.nunique()
Out[281]:
date
2018-01 3
2018-02 3
2019-01 2
2019-02 3
Freq: M, Name: customers, dtype: int64
答案 1 :(得分:1)
尝试一下:
df['date'] = pd.to_datetime(df['date'])
df = df.set_index('date')
df.groupby(df.index.to_period('M'))['customers'].nunique()