我想以2位精度對列進行除法,但我需要確保它在groupby級別上匯總到所需的數字(200)。我不確定解決這個問題的最佳方法是什么。例:vehicle | count | result | calculationford | 2 | 100 | round(200/count, 2) = 100ford | 2 | 100 | 200 - 100 = 100chevrolet | 3 | 66.67 | round(200/count, 2) = 66.67chevrolet | 3 | 66.67 | round(200/count, 2) = 66.67chevrolet | 3 | 66.66 | 200 - 66.67 - 66.67 = 66.66
1 回答

HUH函數
TA貢獻1836條經驗 獲得超4個贊
您可以將殘差添加到組的最后一個元素,即
df['result'] = df.groupby('vehicle', as_index=False).transform(lambda gr: round(200/len(gr), 2))
def add_resid(gr: pd.DataFrame):
gr['result'].iloc[-1] += 200 - gr['result'].sum()
return gr
df['result'] = df.groupby('vehicle', as_index=False).apply(add_resid)
顯然,如果你有一個大團體,這將累積錯誤。另一種方法是以“滾動”方式分配殘差。
添加回答
舉報
0/150
提交
取消