python - 在 Pandas 中的分组数据帧中减去值
问题描述
我有一组 ID 和时间戳,并希望通过获取按 ID 分组的最旧/最早时间戳的差异来计算“每个 ID 所用的总时间”。
数据
id timestamp
1 2018-02-01 03:00:00
1 2018-02-01 03:01:00
2 2018-02-02 10:03:00
2 2018-02-02 10:04:00
2 2018-02-02 11:05:00
预期结果
(我希望将增量转换为分钟)
id delta
1 1
2 62
我有一个 for 循环,但它非常慢(1M+ 行需要 10+ 分钟)。我想知道这是否可以通过熊猫功能实现?
# gb returns a DataFrameGroupedBy object, grouped by ID
gb = df.groupby(['id'])
# Create the resulting df
cycletime = pd.DataFrame(columns=['id','timeDeltaMin'])
def calculate_delta():
for id, groupdf in gb:
time = groupdf.timestamp
# returns timestamp rows for the current id
time_delta = time.max() - time.min()
# convert Timedelta object to minutes
time_delta = time_delta / pd.Timedelta(minutes=1)
# insert result to cycletime df
cycletime.loc[-1] = [id,time_delta]
cycletime.index += 1
考虑下一步尝试:
- 多处理
解决方案
首先确保日期时间正常:
df.timestamp = pd.to_datetime(df.timestamp)
现在找出每个 id 的最大值和最小值之差的分钟数:
import numpy as np
>>> (df.timestamp.groupby(df.id).max() - df.timestamp.groupby(df.id).min()) / np.timedelta64(1, 'm')
id
1 1.0
2 62.0
Name: timestamp, dtype: float64
推荐阅读
- pandas - 从 Pandas 中的 Pickled DataFrame 加载单个系列
- c# - 上一个任务完成后调用异步方法
- r - 如何使用 LaTeX 替代 {} 以将 R/exams 完形填空问题导入带有 LaTeX 代码的 Moodle?
- c - 在不链接 c 标准库的情况下使用编译器内置函数
- c++ - 声明类内向量的大小
- file-upload - 试图找到一种在 symfony 5 中调整上传图像大小的方法
- javascript - 如何在 React 路由器中使用 :params
- react-native - 如何在反应导航中实现标题左侧的按钮
- java - 如果没有互联网连接/wifi/移动数据(JAVA_CODE),如何将第二个活动支持到第一个活动
- php - 没有 CLI 终端的 PHP 调用 Laravel Artisan