Joh*_*ohn 3 python indexing datetime pandas
我有一个看起来像的熊猫系列
Attribute DateEvent Value
Type A 2015-04-01 4
2015-04-02 5
2015-04-05 3
Type B 2015-04-01 1
2015-04-03 4
2015-04-05 1
Run Code Online (Sandbox Code Playgroud)
我的值转换为一个滚动的总和(比方说,过去2天),同时确保以说明我DateEvent指数缺少的日期(假设起始日期和它的结束日期是如何全方位的?(例如,2015-04-03和2015-04-04是缺少A型,并且2015-04-02与2015-04-04缺少类型B)。
我对您想要的东西做了一些假设,请澄清:
Value = NaN。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)
Run Code Online (Sandbox Code Playgroud)
这是它的样子。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
Run Code Online (Sandbox Code Playgroud)
根据此答案,您必须重新构建索引,然后重新索引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)
Run Code Online (Sandbox Code Playgroud)
缺少的日期已添加,带有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
Run Code Online (Sandbox Code Playgroud)
现在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()
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
最后说明:不知道为什么现在有两个Attribute索引列,请让我知道是否有人知道。
编辑:原来类似的问题被问到这里。看看这个。