from itertools import product df2 = df1.reindex(index=list(product(df1.index.get_level_values(0).unique(),[f'{i}' for i in np.arange(1,8,1)])),fill_value=0)
df1 = df.pivot_table(index="医院",columns="月",values="总计",aggfunc="sum").reindex(columns=range(1,13)).fillna(0).cumsum(axis=1) df1.columns = [f"{c}月" for c in df1.columns]