python - 重置数据框中的时间戳并计算时间
问题描述
所以我在数据框中的时间戳看起来像这样:
In [18]: df['time'].head(1)
Out[18]: 2021-10-05 12:00:00.000000+00:00
In [19]: df['time'].tail(1)
Out[19]: 2021-10-07 12:00:00.000000+00:00
我想要一个新专栏(time_new)。在那里,第一个时间戳必须重置为 0,所以起点是 0。然后它只计算小时、秒和毫秒。因此,在这种情况下,最后有 48 小时。下表用于说明。
| index | time | time_new |
|------- |---------------------------------- |---------- |
| 0 | 2021-10-05 12:00:00.000000+00:00 | 00:00:00.000 |
| 1 | 2021-10-05 13:00:00.000000+00:00 | 01:00:00.000 |
| 2 | 2021-10-05 13:00:00.001000+00:00 | 01:00:00.001 |
| 3 | 2021-10-06 02:00:00.000000+00:00 | 14:00:00.000 |
| 4 | 2021-10-07 12:00:00.000000+00:00 | 48:00:00.000 |
解决方案
对于 timedeltas 减去列的最小值:
df['time_new'] = df['time'].sub(df['time'].min())
或列的第一个值:
df['time_new'] = df['time'].sub(df['time'].iat[0])
如果格式很重要,请使用自定义函数:
def format_timedelta(x):
ts = x.total_seconds()
hours, remainder = divmod(ts, 3600)
minutes, seconds = divmod(remainder, 60)
return ('{:02d}:{:02d}:{:.3f}').format(int(hours), int(minutes), seconds)
df['time_new'] = df['time'].sub(df['time'].min()).apply(format_timedelta)
print (df)
time time_new
0 2021-10-05 12:00:00+00:00 00:00:0.000
1 2021-10-05 13:00:00+00:00 01:00:0.000
2 2021-10-05 13:00:00.001000+00:00 01:00:0.001
3 2021-10-06 02:00:00+00:00 14:00:0.000
4 2021-10-07 12:00:00+00:00 48:00:0.000
对于mean
:
avg = df.loc[df['time_new'] <= pd.Timedelta('01:00:00'), 'vibration'].mean()
推荐阅读
- sublimetext4 - 如何只为一个文件 ST4 设置自动完成?
- logging - 日志基础 2 序言
- c++20 - PPL 并发和 co_await 导致 lambda 捕获变量在挂起时超出范围
- ruby - Capybara - have_css 在不应该匹配空字符串时匹配
- reactjs - 如何从 Amplify-React 调用现有的 Lambda 函数?
- php - 如何使用 Inertia JS 在 Laravel 中默认编辑或删除身份验证的 URL?
- firebase - 上传符号成功后 Firebase 缺少 dSYM
- excel - 对命名范围之外的单元格进行更改时出现 VBA Excel 运行时错误“1004”
- jquery - 当有人滚动到 ID 时开始编号计数器 JQuery 动画
- terraform - Terraform init 报告无法通过 Github Actions 查询提供程序包