python - 如何使用熊猫数据框按秒重新采样累积的数据并每天重置
问题描述
我每天积累的数据如下。它在每天开始时(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
任何帮助,将不胜感激。
解决方案
直接计算差异,无需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 上测试
推荐阅读
- ffmpeg - 在 MP3 中创建 Xing 或 Info 标记时,我可以使用任何 MP3 标头还是必须匹配其他帧?
- excel - 当 if 语句验证检查失败并提示 msgbox 时,Userform Next 按钮不起作用
- c++ - 如何修复“函数_main中引用的未解析的外部符号_gladLoadGLLoader”和“未解析的外部符号_glad_glViewport”?
- amazon-web-services - Spark + S3 + IAM 角色
- java - 如何在嵌套类中调用泛型
- swift - 播放声音时如何修复 66671 AudioQueueInternalNotifyRunning 错误?
- assembly - 为什么 GCC 会生成带有一堆无用 JMP 指令的代码?
- c++ - Am I Setting up this Hash Table Correctly?
- java - 错误:程序类型已存在:com.rom4ek.arcnavigationview.R
- python - 具有增量添加的 Python 列表操作