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

按ID分组为各日期列生成Min和Max列

Solution

To achieve your desired output, you can use pandas' groupby combined with agg() to specify multiple aggregation functions (min and max) for each date column. Here's a step-by-step implementation:

Step 1: Prepare the DataFrame

First, create your sample DataFrame (or load your actual data):

import pandas as pd

data = {
    'ID': [1,1,1,2,2,2],
    'DateMade': ['01/01/2020', '01/01/2020', '01/01/2020', '03/04/2020', '05/06/2020', '01/01/2021'],
    'DelDate': ['05/06/2020', '07/06/2020', '07/06/2020', '07/08/2020', '23/08/2020', '31/08/2020'],
    'ExpDate': ['06/05/2022', '07/05/2022', '09/09/2022', '15/12/2022', '31/12/2022', '09/01/2023']
}

df = pd.DataFrame(data)

Step 2: Convert Date Columns to Datetime

To ensure accurate min/max calculations (string-based date comparison can fail), convert the date columns to datetime objects:

date_columns = ['DateMade', 'DelDate', 'ExpDate']
df[date_columns] = df[date_columns].apply(pd.to_datetime, dayfirst=True)

Step 3: Group by ID and Aggregate Min/Max

Use groupby('ID') and agg() to apply both min and max to each date column:

# Perform grouping and aggregation
grouped_df = df.groupby('ID').agg({
    'DateMade': ['min', 'max'],
    'DelDate': ['min', 'max'],
    'ExpDate': ['min', 'max']
})

# Flatten the multi-level column names (e.g., ('DateMade', 'min') becomes 'DateMade_Min')
grouped_df.columns = ['_'.join(col).capitalize() for col in grouped_df.columns]

# Reset index to make ID a regular column instead of the index
result_df = grouped_df.reset_index()

Step 4: Optional - Convert Dates Back to String Format

If you need the dates in the original DD/MM/YYYY string format:

result_df.iloc[:, 1:] = result_df.iloc[:, 1:].apply(lambda x: x.dt.strftime('%d/%m/%Y'))

Final Result

The resulting DataFrame will match your desired output:

IDDateMade_MinDateMade_MaxDelDate_MinDelDate_MaxExpDate_MinExpDate_Max
101/01/202001/01/202005/06/202007/06/202006/05/202209/09/2022
203/04/202001/01/202107/08/202031/08/202015/12/202209/01/2023

Key Notes

  • Using agg() with a dictionary lets you specify different aggregation functions per column, which is perfect for your multi-column scenario.
  • Converting dates to datetime ensures that min/max calculations are correct (e.g., "31/08/2020" is recognized as later than "07/08/2020", which wouldn't happen with string comparison).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 07:20:32