首页 > 解决方案 > 在 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

考虑下一步尝试:
- 多处理

标签: pythonpandasdataframedata-analysis

解决方案


首先确保日期时间正常:

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

推荐阅读