按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:
| ID | DateMade_Min | DateMade_Max | DelDate_Min | DelDate_Max | ExpDate_Min | ExpDate_Max |
|---|---|---|---|---|---|---|
| 1 | 01/01/2020 | 01/01/2020 | 05/06/2020 | 07/06/2020 | 06/05/2022 | 09/09/2022 |
| 2 | 03/04/2020 | 01/01/2021 | 07/08/2020 | 31/08/2020 | 15/12/2022 | 09/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
相关产品推荐
相关产品推荐

