如何在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:
- Ensure Time Column is Datetime: First, convert your
timecolumn to a datetime type (if it isn't already) so we can perform time calculations. - Group by Date: Use
groupby('date')to process each date's data separately. - 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() / 60converts the time difference to minutes, andround(..., 0)gives us whole numbers.transformapplies the calculation to each group and returns a Series that aligns with the original DataFrame's index, so we can directly assign it to thedifcolumn.
内容的提问来源于stack exchange,提问作者Raúl Casado
相关产品推荐
相关产品推荐

