如何基于缺失的Cohort_index值为DataFrame自动填充新行?
问题:补全分组内缺失的Cohort_index行
我有一个包含week、co_week、Revenue、Cohort_index列的DataFrame,数据如下:
| week | co_week | Revenue | Cohort_index |
|---|---|---|---|
| 19/09/2021 | 01/10/2021 | 120 | 0 |
| 19/09/2021 | 03/10/2021 | 150 | 1 |
| 19/09/2021 | 06/10/2021 | 223 | 2 |
| 19/09/2021 | 07/10/2021 | 256 | 4 |
| 19/09/2021 | 08/10/2021 | 340 | 5 |
| 20/09/2021 | 06/10/2021 | 126 | 0 |
| 20/09/2021 | 07/10/2021 | 234 | 1 |
当前同一week分组下存在Cohort_index缺失(比如示例中缺失值3),需要自动检测缺失的Cohort_index,插入对应新行,新行其余列值复制自前一行,同时更新DataFrame索引。由于数据量庞大,无法通过硬编码添加行,以下是不可用的硬编码示例:
new_raw = DataFrame({"week": 19/09/2022, "co_week": 06/10/2021, "Revenue": 223 ,"Cohort_index":3}) df = df.append(new_raw, ignore_index=False)
期望输出的DataFrame如下:
| week | co_week | Revenue | Cohort_index |
|---|---|---|---|
| 19/09/2021 | 01/10/2021 | 120 | 0 |
| 19/09/2021 | 03/10/2021 | 150 | 1 |
| 19/09/2021 | 06/10/2021 | 223 | 2 |
| 19/09/2021 | 06/10/2021 | 223 | 3 |
| 19/09/2021 | 07/10/2021 | 256 | 4 |
| 19/09/2021 | 08/10/2021 | 340 | 5 |
| 20/09/2021 | 06/10/2021 | 126 | 0 |
| 20/09/2021 | 07/10/2021 | 234 | 1 |
解决方案
可以通过分组处理+前向填充的方式实现,代码如下:
import pandas as pd # 构造原DataFrame(如果已有数据可跳过此步) data = [ ["19/09/2021", "01/10/2021", 120, 0], ["19/09/2021", "03/10/2021", 150, 1], ["19/09/2021", "06/10/2021", 223, 2], ["19/09/2021", "07/10/2021", 256, 4], ["19/09/2021", "08/10/2021", 340, 5], ["20/09/2021", "06/10/2021", 126, 0], ["20/09/2021", "07/10/2021", 234, 1] ] df = pd.DataFrame(data, columns=["week", "co_week", "Revenue", "Cohort_index"]) def fill_missing_cohort(group): # 生成当前分组的完整Cohort_index序列(从0到最大索引值) max_cohort = group["Cohort_index"].max() full_cohorts = pd.DataFrame({"Cohort_index": range(0, max_cohort + 1)}) # 合并完整序列与原分组数据 merged = pd.merge(full_cohorts, group, on="Cohort_index", how="left") # 填充week列(同一分组week值唯一) merged["week"] = group["week"].iloc[0] # 前向填充co_week和Revenue,复制前一行的值 merged[["co_week", "Revenue"]] = merged[["co_week", "Revenue"]].ffill() return merged # 按week分组处理,合并结果并重置索引 result_df = df.groupby("week", group_keys=False).apply(fill_missing_cohort).reset_index(drop=True) # 输出结果 print(result_df)
代码说明
- 分组处理:按
week分组,对每个分组单独处理缺失的Cohort_index - 生成完整序列:对每个分组,生成从0到该分组最大
Cohort_index的完整索引序列 - 合并与填充:将完整序列与原分组数据合并,
week直接取分组的唯一值,co_week和Revenue用前向填充(ffill)复制前一行的值,自动补全缺失行 - 重置索引:合并所有分组结果后重置索引,保证索引连续
内容的提问来源于stack exchange,提问作者Maikel Bastawrous
相关产品推荐
相关产品推荐

