创建一个缺少月份序列的行

Create a row where sequence of month is Missing

我需要帮助在 python 中构建数据框,如果缺少月份序列,它将创建一个新行,月收入为 0。对月份序列的检查将一直持续到总年龄特定的 VIN。以下是数据框。

当前Df:

VIN Total Age Months Monthly Revenue
v1 10 00 1513
v1 10 05 1108
v1 10 07 4330
v1 10 09 7121
v2 08 01 1998
v2 08 04 4997
v2 08 05 8528
v2 08 06 1783
v2 08 07 9628
v2 08 08 2082

OutputDf:

VIN Total Age Months Monthly Revenue
v1 10 00 1513
v1 10 01 00
v1 10 02 00
v1 10 03 00
v1 10 04 00
v1 10 05 1108
v1 10 06 00
v1 10 07 433
v1 10 08 00
v1 10 09 7121
v1 10 10 00
V2 08 00 00
v2 08 01 1998
v2 08 02 00
v2 08 03 00
v2 08 04 4997
v2 08 05 8528
v2 08 06 1783
v2 08 07 9628
v2 08 08 2082

IIUC:

def reindexer(x):
    x = (
        x.reset_index()
        .set_index("Months")
        .reindex(range(0, x["Total Age"].max() + 1))
    )
    x["Total Age"] = x["Total Age"].ffill().bfill().astype(int)
    x["Monthly Revenue"] = x["Monthly Revenue"].fillna(0)
    return x


x = (
    df.groupby("VIN")
    .apply(reindexer)
    .drop(columns=["index", "VIN"])
    .reset_index()
)
print(x.to_markdown())

打印:

VIN Months Total Age Monthly Revenue
0 v1 0 10 1513
1 v1 1 10 0
2 v1 2 10 0
3 v1 3 10 0
4 v1 4 10 0
5 v1 5 10 1108
6 v1 6 10 0
7 v1 7 10 4330
8 v1 8 10 0
9 v1 9 10 7121
10 v1 10 10 0
11 v2 0 8 0
12 v2 1 8 1998
13 v2 2 8 0
14 v2 3 8 0
15 v2 4 8 4997
16 v2 5 8 8528
17 v2 6 8 1783
18 v2 7 8 9628
19 v2 8 8 2082

已更新个月不超过总年龄