我对你想要什么做了几个假设,请澄清:
- 您希望将缺少日期的行视为具有
Value = NaN。
- 因此,只要滚动窗口中缺少日期,过去 2 天滚动总和应返回
NaN。
- 您想要计算滚动总和在每个组内
Type A 和 Type B
如果我猜对了,
创建样本数据集
import pandas as pd
import numpy as np
import io
datastring = io.StringIO(
"""
Attribute,DateEvent,Value
Type A,2017-04-02,1
Type A,2017-04-03,2
Type A,2017-04-04,3
Type A,2017-04-05,4
Type B,2017-04-02,1
Type B,2017-04-03,2
Type B,2017-04-04,3
Type B,2017-04-05,4
""")
s = pd.read_csv(
datastring,
index_col=['Attribute', 'DateEvent'],
parse_dates=True)
print(s)
这就是它的样子。 Type A 和 Type B 中的每一个都缺少 2017-04-01。
Value
Attribute DateEvent
Type A 2017-04-02 1
2017-04-03 2
2017-04-04 3
2017-04-05 4
Type B 2017-04-02 1
2017-04-03 2
2017-04-04 3
2017-04-05 4
解决方案
根据this answer,您必须重建索引,然后重新索引您的Series 以获得包含所有日期的索引。
# reconstruct index with all the dates
dates = pd.date_range("2017-04-01","2017-04-05", freq="1D")
attributes = ["Type A", "Type B"]
# create a new MultiIndex
index = pd.MultiIndex.from_product([attributes,dates],
names=["Attribute","DateEvent"])
# reindex the series
sNew = s.reindex(index)
添加了缺少的日期,Value = NaN。
Value
Attribute DateEvent
Type A 2017-04-01 NaN
2017-04-02 1.0
2017-04-03 2.0
2017-04-04 3.0
2017-04-05 4.0
Type B 2017-04-01 NaN
2017-04-02 1.0
2017-04-03 2.0
2017-04-04 3.0
2017-04-05 4.0
现在将Series 按Attribute 索引列分组,并应用大小为2 和sum() 的滚动窗口
# group the series by the `Attribute` column
grouped = sNew.groupby(level="Attribute")
# Apply a 2 day rolling window
summed = grouped.rolling(2).sum()
最终输出
Value
Attribute Attribute DateEvent
Type A Type A 2017-04-01 NaN
2017-04-02 NaN
2017-04-03 3.0
2017-04-04 5.0
2017-04-05 7.0
Type B Type B 2017-04-01 NaN
2017-04-02 NaN
2017-04-03 3.0
2017-04-04 5.0
2017-04-05 7.0
最后说明:不知道为什么现在有两个 Attribute 索引列,如果有人知道,请告诉我。
编辑:结果类似的问题被问到here。看看吧。
来源:How to fill in missing values with a multiIndex