首页 > 解决方案 > 如何使用熊猫数据框按秒重新采样累积的数据并每天重置

问题描述

我每天积累的数据如下。它在每天开始时(00:00:00)重置为 0。

index
11/05 23:59:48  100
11/05 23:59:59  150
11/06 00:00:01  10
11/06 00:00:02  20
11/06 00:00:12  40

我需要在 10 秒内获得绝对(非累积)数字,如下所示。

index
11/05 23:59:49  Nan
11/05 23:59:59  50
11/06 00:00:09  20
11/06 00:00:19  20

我做了类似下面的事情,但它在每天的第一个时段(例如:11/06 00:00:09)给出了 Nan 值。

df.groupby(df.index.levels[0].dt).resample('10S').last().diff()
index
11/05 23:59:49  Nan
11/05 23:59:59  50
11/06 00:00:09  Nan
11/06 00:00:19  20

任何帮助,将不胜感激。

标签: pythonpandasdataframe

解决方案


直接计算差异,无需groupby重采样。一天的开始可以通过diff-ne构造来检测,并且可以通过将先前的累积值加回来对这些位置进行所需的校正。

数据

这里的索引是pd.Timestamp

print(df)
                     total
index                     
2020-11-05 23:59:48    100
2020-11-05 23:59:59    150
2020-11-06 00:00:01     10
2020-11-06 00:00:02     20
2020-11-06 00:00:12     40

代码

# Not accurate for the test data, so replaced
# df2 = df.resample("10S").last()

df2 = df.copy()
df2["new_index"] = df2.index.map(lambda ts: ts + pd.Timedelta(9 - ts.second % 10, unit="s"))
df2 = df2.groupby("new_index").last()

# 1. de-accumulate without groupby
df2["diff"] = df2.diff()
# 2. get date change locations (where diff != 0 Days)
df2["date"] = df2.index.date
df2["add"] = df2["date"].diff().ne("0D")
# 3. add the previous total back
df2.loc[df2["add"], "diff"] += df2["total"].shift()[df2["add"]]

结果

diff列是您想要的。

print(df2)
                     total  diff        date    add
new_index                                          
2020-11-05 23:59:49    100   NaN  2020-11-05   True
2020-11-05 23:59:59    150  50.0  2020-11-05  False
2020-11-06 00:00:09     20  20.0  2020-11-06   True
2020-11-06 00:00:19     40  20.0  2020-11-06  False

在 python 3.7.9 和 pandas 1.1.3 上测试


推荐阅读