如何用Pandas按组计算两列的最大/最小值差值
问题与解决方案
原始数据集
| group_id | from_date | to_date |
|---|---|---|
| 0 | 2020-01-01 | 2020-02-01 |
| 0 | 2020-02-01 | 2020-03-01 |
| 0 | 2020-03-01 | 2020-04-01 |
| 1 | 2020-01-01 | 2020-02-01 |
| 1 | 2020-02-01 | 2020-03-01 |
需求
按group_id分组,计算每组max(to_date) - min(from_date)的天数差,期望结果如下:
| group_id | duration_days |
|---|---|
| 0 | 90 |
| 1 | 60 |
遇到的问题
使用以下代码能正确计算时长,但返回的是包含5行的未分组DataFrame:
groupby(["group_id"]) .apply(lambda x: x.assign(duration_days=(np.max(x["to_date"])-np.min(x["from_date"])).days))
尝试用aggregate方法,但不知道如何实现涉及两列的函数计算。
解决方案
方法1:agg自定义函数
直接在groupby后调用agg,传入自定义函数计算每组天数差,返回分组结果:
import pandas as pd import numpy as np # 假设df为原始DataFrame result = df.groupby("group_id").agg( duration_days=lambda x: (x["to_date"].max() - x["from_date"].min()).days ).reset_index()
方法2:先聚合关键日期再计算
先分别提取每组的最小from_date和最大to_date,再计算天数差,可读性更强:
agg_df = df.groupby("group_id").agg( min_from=("from_date", "min"), max_to=("to_date", "max") ) agg_df["duration_days"] = (agg_df["max_to"] - agg_df["min_from"]).days result = agg_df.drop(columns=["min_from", "max_to"]).reset_index()
方法3:修正apply返回值
若坚持用apply,可让其只返回每组的计算结果,而非给每行赋值:
result = df.groupby("group_id").apply( lambda x: pd.Series({"duration_days": (x["to_date"].max() - x["from_date"].min()).days}) ).reset_index()
以上方法均可得到目标分组结果,其中方法2的可读性最优,便于后续维护。
内容的提问来源于stack exchange,提问作者nlassaux
相关产品推荐
相关产品推荐

