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

按A分组筛选A、B日期绝对时间差最小的行

Solution: Group by Column A and Filter Rows with Smallest Time Difference Between A and B

Let's walk through how to solve this using pandas—it's perfect for this kind of targeted data manipulation.

Original Dataset

First, here's your input data formatted for clarity:

ABC
02002-01-162002-02-28Jack
12002-01-162002-01-30Helen
22002-01-162002-02-28Peter
32002-01-162002-01-30Jud
42002-04-272002-04-30Nick
52002-04-272002-05-25Wendy
62002-04-272002-04-30Bryan
72002-04-272002-05-25Sarah

Step-by-Step Code Implementation

Here's the code to get your desired output, with explanations along the way:

import pandas as pd

# Create the original DataFrame from your data
data = {
    'A': ['2002-01-16', '2002-01-16', '2002-01-16', '2002-01-16',
          '2002-04-27', '2002-04-27', '2002-04-27', '2002-04-27'],
    'B': ['2002-02-28', '2002-01-30', '2002-02-28', '2002-01-30',
          '2002-04-30', '2002-05-25', '2002-04-30', '2002-05-25'],
    'C': ['Jack', 'Helen', 'Peter', 'Jud', 'Nick', 'Wendy', 'Bryan', 'Sarah']
}
df = pd.DataFrame(data)

# Convert date columns from strings to datetime objects (critical for time calculations)
df['A'] = pd.to_datetime(df['A'])
df['B'] = pd.to_datetime(df['B'])

# Calculate absolute day difference between columns A and B
df['time_diff'] = (df['B'] - df['A']).dt.days.abs()

# Group by column A, find the minimum time difference per group, then filter matching rows
min_diff_per_group = df.groupby('A')['time_diff'].transform('min')
result_df = df[df['time_diff'] == min_diff_per_group].drop(columns='time_diff')

# Reset index to match your expected output format (optional but clean)
result_df = result_df.reset_index(drop=True)

print(result_df)

Final Output

Running this code will produce exactly the result you're looking for:

ABC
02002-01-162002-01-30Helen
12002-01-162002-01-30Jud
22002-04-272002-04-30Nick
32002-04-272002-04-30Bryan

Quick Breakdown

  • Datetime Conversion: We turn columns A and B into datetime objects so we can calculate valid time differences (strings won't work for this!).
  • Time Difference Calculation: We compute the absolute number of days between A and B to get a numerical value we can compare.
  • Group & Filter: Using transform('min') lets us fetch the smallest time difference for each group of A values. We then filter the original DataFrame to keep only rows where the time difference matches that group's minimum.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:21:04