[問題] 關於DataFrame分組計算的問題

作者: sonicstars (昊旱)   2023-05-31 22:14:52
首先是我的資料示意
https://imgur.com/a/59jwXrk
我並沒有呈現出我全部的資料,全部的資料有一年
其中藍色的部份就是我的變數Daliy_profit_milage
是個DataFrame,index是日期且已經轉為datetime型式
(我貼到excel才截圖,有些細節被隱藏,然後index的欄位名稱其實是'date')
接著我執行以下程式碼
gp_m=pd.Grouper(level='date',freq='M')
MaxMonthlyMilage = Daliy_profit_milage.iloc[:,1].groupby(gp_m).max()
我的程式執行到這邊還沒有問題,也成功找出當月最大里程數
接著我想要將每日獲利除上對應月份的當月最大里程數
Daliy_profit_milage.iloc[:,0].groupby(gp_m) / MaxMonthlyMilage
就跳出了這個錯誤訊息
ValueError:operands could not be broadcast together with shapes (12,2) (12,)
以及這個Warning
VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences
(which is a list-or-tuple of lists-or-tuples-or ndarrays with different
lengths or shapes) is deprecated. If you meant to do this, you must specify
'dtype=object' when creating the ndarray.
我蠻確定我對程式碼的理解有錯誤,想請問一.我可以怎麼改善我的程式碼?
二.假如Pandas套件其實無法滿足我的運算需求,我有其他的選擇嗎?
先提前感謝各位大大了
作者: lycantrope (阿寬)   2023-05-31 23:47:00
groupby後直接apply算daily_profit/mile.max()
作者: sonicstars (昊旱)   2023-06-01 07:47:00
原來如此,感謝大大幫忙
作者: lycantrope (阿寬)   2023-06-01 21:00:00
f = lambda d: d.iloc[...,0]/ d.iloc[...,1].max()Daliy_profit_milage.groupby(gp_m).apply(f)是daily不是daliy
作者: celestialgod (天)   2023-06-02 11:36:00
作者: sonicstars (昊旱)   2023-06-05 20:45:00
解決了,感謝各位大大

Links booklink

Contact Us: admin [ a t ] ucptt.com