作者sonicstars (昊旱)
看板Python
標題[問題] 關於DataFrame分組計算的問題
時間Wed May 31 22:14:52 2023
首先是我的資料示意
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
→ lycantrope: groupby後直接apply算daily_profit/mile.max() 05/31 23:47
→ sonicstars: 原來如此,感謝大大幫忙 06/01 07:47
→ sonicstars: 抱歉,我參照著做之後,發現還是跳了error 06/01 15:41
→ sonicstars: 我參考lycantrope的意見改成了以下程式碼 06/01 15:43
→ sonicstars: Daliy_profit_milage.groupby(gp_m).apply(Daliy_prof 06/01 15:43
→ sonicstars: _milage.iloc[:,0] / Daliy_profit_milage.iloc[:,1]. 06/01 15:44
→ sonicstars: max() ) 06/01 15:44
→ sonicstars: 跳出錯誤訊息TypeError: unhashable type: 'Series' 06/01 15:44
→ lycantrope: f = lambda d: d.iloc[...,0]/ d.iloc[...,1].max() 06/01 21:00
→ lycantrope: Daliy_profit_milage.groupby(gp_m).apply(f) 06/01 21:00
→ lycantrope: 是daily不是daliy 06/01 21:02
→ sonicstars: 解決了,感謝各位大大 06/05 20:45