[问题] 关于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