作者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://webptt.com/cn.aspx?n=bbs/Python/M.1685542496.A.F33.html
1F:→ lycantrope: groupby後直接apply算daily_profit/mile.max() 05/31 23:47
2F:→ sonicstars: 原来如此,感谢大大帮忙 06/01 07:47
3F:→ sonicstars: 抱歉,我参照着做之後,发现还是跳了error 06/01 15:41
4F:→ sonicstars: 我参考lycantrope的意见改成了以下程式码 06/01 15:43
5F:→ sonicstars: Daliy_profit_milage.groupby(gp_m).apply(Daliy_prof 06/01 15:43
6F:→ sonicstars: _milage.iloc[:,0] / Daliy_profit_milage.iloc[:,1]. 06/01 15:44
7F:→ sonicstars: max() ) 06/01 15:44
8F:→ sonicstars: 跳出错误讯息TypeError: unhashable type: 'Series' 06/01 15:44
9F:→ lycantrope: f = lambda d: d.iloc[...,0]/ d.iloc[...,1].max() 06/01 21:00
10F:→ lycantrope: Daliy_profit_milage.groupby(gp_m).apply(f) 06/01 21:00
11F:→ lycantrope: 是daily不是daliy 06/01 21:02
13F:→ sonicstars: 解决了,感谢各位大大 06/05 20:45