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

看板Python作者 (昊旱)時間11月前 (2023/05/31 22:14), 編輯推噓0(0013)
留言13則, 3人參與, 11月前最新討論串1/1
首先是我的資料示意 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套件其實無法滿足我的運算需求,我有其他的選擇嗎? 先提前感謝各位大大了 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.113.87.78 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1685542496.A.F33.html

05/31 23:47, 11月前 , 1F
groupby後直接apply算daily_profit/mile.max()
05/31 23:47, 1F

06/01 07:47, 11月前 , 2F
原來如此,感謝大大幫忙
06/01 07:47, 2F

06/01 15:41, 11月前 , 3F
抱歉,我參照著做之後,發現還是跳了error
06/01 15:41, 3F

06/01 15:43, 11月前 , 4F
我參考lycantrope的意見改成了以下程式碼
06/01 15:43, 4F

06/01 15:43, 11月前 , 5F
Daliy_profit_milage.groupby(gp_m).apply(Daliy_prof
06/01 15:43, 5F

06/01 15:44, 11月前 , 6F
_milage.iloc[:,0] / Daliy_profit_milage.iloc[:,1].
06/01 15:44, 6F

06/01 15:44, 11月前 , 7F
max() )
06/01 15:44, 7F

06/01 15:44, 11月前 , 8F
跳出錯誤訊息TypeError: unhashable type: 'Series'
06/01 15:44, 8F

06/01 21:00, 11月前 , 9F
f = lambda d: d.iloc[...,0]/ d.iloc[...,1].max()
06/01 21:00, 9F

06/01 21:00, 11月前 , 10F
Daliy_profit_milage.groupby(gp_m).apply(f)
06/01 21:00, 10F

06/01 21:02, 11月前 , 11F
是daily不是daliy
06/01 21:02, 11F

06/02 11:36, 11月前 , 12F

06/05 20:45, 11月前 , 13F
解決了,感謝各位大大
06/05 20:45, 13F
文章代碼(AID): #1aTrPWyp (Python)
文章代碼(AID): #1aTrPWyp (Python)