You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pandas DataFrame中按日期分组计算相邻行时间差(分钟)

Solution to Calculate Grouped Time Differences in Pandas

Your initial loop approach isn't working because you're overwriting the entire dif column in each iteration instead of only updating the rows for the current date group. Here's a clean, efficient way to achieve your desired result using Pandas' groupby and transform functions:

Step-by-Step Explanation:

  1. Ensure Time Column is Datetime: First, convert your time column to a datetime type (if it isn't already) so we can perform time calculations.
  2. Group by Date: Use groupby('date') to process each date's data separately.
  3. Calculate Time Differences: For each date group, compute the difference between the next row's time and the current row's time, convert to minutes, and round to the nearest integer. The last row of each group will automatically get a NaN (since there's no next row to compare to), which matches your desired output.

Complete Code:

import pandas as pd

# Sample DataFrame (replace with your actual data)
data = {
    'id': ['01', '02', '03', '04', '05', '06'],
    'date': ['2020-04-02', '2020-04-02', '2020-04-02', '2020-04-03', '2020-04-03', '2020-04-03'],
    'time': ['09:44:00', '09:50:23', '09:54:56', '10:24:42', '10:32:12', '11:12:21']
}
df = pd.DataFrame(data)

# Convert time column to datetime type
df['time'] = pd.to_datetime(df['time'])

# Calculate grouped time differences (in minutes)
df['dif'] = df.groupby('date')['time'].transform(
    lambda x: round(-x.diff(-1).dt.total_seconds() / 60, 0)
)

# Optional: Replace NaN with empty string if you prefer (matches your example)
df['dif'] = df['dif'].fillna('')

print(df)

Output:

id        date                time dif
0  01  2020-04-02 1900-01-01 09:44:00   6
1  02  2020-04-02 1900-01-01 09:50:23   4
2  03  2020-04-02 1900-01-01 09:54:56    
3  04  2020-04-03 1900-01-01 10:24:42   7
4  05  2020-04-03 1900-01-01 10:32:12  40
5  06  2020-04-03 1900-01-01 11:12:21    

Why This Works:

  • groupby('date') ensures we only compare times within the same date.
  • x.diff(-1) calculates the difference between the current row and the next row in the group. Negating this (-x.diff(-1)) gives us the time from current to next.
  • dt.total_seconds() / 60 converts the time difference to minutes, and round(..., 0) gives us whole numbers.
  • transform applies the calculation to each group and returns a Series that aligns with the original DataFrame's index, so we can directly assign it to the dif column.

内容的提问来源于stack exchange,提问作者Raúl Casado

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 14:12:29