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

Pandas中按Label分组计算Date列时间差的技术问询

Solution for Calculating Time Differences Between Adjacent Records with Label=20

Hey Keithx, let's work through this problem step by step to get the timedelta you need:

Step 1: Make sure your Date column is datetime-formatted

First, we need to convert the Date column from strings to datetime type — this is essential for calculating valid time differences:

import pandas as pd

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

Step 2: Filter rows where Label equals 20

Next, we'll create a subset of your DataFrame that only includes records with Label=20:

label_20_df = df[df['Label'] == 20].copy()  # Using copy() avoids potential SettingWithCopy warnings

Step 3: Calculate the time delta between consecutive records

Use the shift() method to compare each row's Date with the previous row's Date, then subtract to get the timedelta:

label_20_df['timedelta'] = label_20_df['Date'] - label_20_df['Date'].shift(1)

Final Output

After running these steps, your label_20_df will look like this:

DateLabeltimedelta
2017-03-22 15:16:4520NaT
2017-03-22 22:10:23200 days 06:53:38
2017-03-24 10:11:13201 days 12:00:50
2017-03-25 14:02:54201 days 03:51:41

A quick note: The first row shows NaT (Not a Time) because there's no prior record to compare it against. If you want to remove this row, just add label_20_df = label_20_df.dropna(subset=['timedelta']) at the end.

内容的提问来源于stack exchange,提问作者Keithx

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:53:02