python 实现分组求和与分组累加求和代码
我就废话不多说了,大家还是直接看代码吧!
#-*-encoding=utf-8-*- importpandasaspd data=['abc','abc','abc','asc','ase','ase','ase'] num=[1,2,2,1,2,1,2] df1=pd.DataFrame({'name':data,'num':num}) print(df1) df1['mmm']=df1['num'] df2=df1.groupby(['name','num'],as_index=False).count() print(df2) df2.sort_values(['name','num'],ascending=[1,1],inplace=True) print(df2) df2['sum']=df2.groupby(['name'])['mmm'].cumsum() print(df2) kk=df2.groupby(['name'],as_index=False)['num'].sum() print(kk) df3=pd.merge(df2,kk,on='name',how='left',) print(df3) df3['ratio']=df3['sum']/df3['num_y'] df3.columns=['name','num','mmm','sum','numsum','ratio'] print(df3) df4=df3.groupby(['mmm'],as_index=False)['ratio'].mean() print(df4)
运行:
namenum 0abc1 1abc2 2abc2 3asc1 4ase2 5ase1 6ase2 namenummmm 0abc11 1abc22 2asc11 3ase11 4ase22 namenummmm 0abc11 1abc22 2asc11 3ase11 4ase22 namenummmmsum 0abc111 1abc223 2asc111 3ase111 4ase223 namenum 0abc3 1asc1 2ase3 namenum_xmmmsumnum_y 0abc1113 1abc2233 2asc1111 3ase1113 4ase2233 namenummmmsumnumsumratio 0abc11130.333333 1abc22331.000000 2asc11111.000000 3ase11130.333333 4ase22331.000000 mmmratio 010.555556 121.000000 Processfinishedwithexitcode0
补充知识:python项目篇-对符合条件的某个字段进行求和,聚合函数annotate(),aggregate()函数
对符合条件的某个字段求和
需求是,计算每日的收入和
1、
new_dayincome=request.POST.get("dayincome_time",None) #total_income=models.bathAccount.objects.filter(dayBath=new_dayincome).aggregate(nums=Sum('priceBath')) total_income=models.bathAccount.objects.values('priceBath').annotate(nums=Sum('priceBath')).filter(dayBath=new_dayincome) print("total_income",total_income[0]['nums'])
输出结果:total_income132
2、
fromdjango.db.modelsimportSum,Count new_dayincome=request.POST.get("dayincome_time",None) total_income=models.bathAccount.objects.filter(dayBath=new_dayincome).aggregate(nums=Sum('priceBath')) print("total_income",total_income['nums'])
输出结果:total_income572
第二种输出的是正确的数字
以上这篇python实现分组求和与分组累加求和代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。