Pandas中按Label分组计算Date列时间差的技术问询
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:
| Date | Label | timedelta |
|---|---|---|
| 2017-03-22 15:16:45 | 20 | NaT |
| 2017-03-22 22:10:23 | 20 | 0 days 06:53:38 |
| 2017-03-24 10:11:13 | 20 | 1 days 12:00:50 |
| 2017-03-25 14:02:54 | 20 | 1 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

