我想要滚动最大值一个缺少“年”的数据框。所以我有这个数据框:
df = pd.DataFrame({"customer":["A","A","B","B"],"Year":[16,17,18,19,20,16],"Value":[3,np.nan,2,1,4,7,5]})
年份未排序且年份缺失。
所以 B 没有第 18 年的值。
我想得到:
客户 | 年 | 价值 |
---|---|---|
A | 16-18 | 3 |
A | 17-19 | 2 |
A | 18-20 | 4 |
B | 16-18 | 5 |
B | 17-19 | 7 |
B | 18-20 | 7 |
我试过了:
first pivot and melt to get all years in the data
dfpivot=df.pivot_table(index="customer",columns="year",values="value").reset_index()
dfmelt=pd.melt(dfpivot,id_vars="customer",value_vars=[16,20],value_name="value")
dfmelt.sort_values(by=["year"]).groupby(["customer"]).rolling(3,1).max()
dfmelt.sort_values(by=["year"]).groupby(["customer"]).rolling(3,1).apply(lambda x: np.nanmax(x))
但是我丢失了我不想要的年份列...