python 實現(xiàn)分組求和與分組累加求和代碼
我就廢話不多說了,大家還是直接看代碼吧!
# -*- encoding=utf-8 -*- import pandas as pd 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)
運行:
name num 0 abc 1 1 abc 2 2 abc 2 3 asc 1 4 ase 2 5 ase 1 6 ase 2 name num mmm 0 abc 1 1 1 abc 2 2 2 asc 1 1 3 ase 1 1 4 ase 2 2 name num mmm 0 abc 1 1 1 abc 2 2 2 asc 1 1 3 ase 1 1 4 ase 2 2 name num mmm sum 0 abc 1 1 1 1 abc 2 2 3 2 asc 1 1 1 3 ase 1 1 1 4 ase 2 2 3 name num 0 abc 3 1 asc 1 2 ase 3 name num_x mmm sum num_y 0 abc 1 1 1 3 1 abc 2 2 3 3 2 asc 1 1 1 1 3 ase 1 1 1 3 4 ase 2 2 3 3 name num mmm sum numsum ratio 0 abc 1 1 1 3 0.333333 1 abc 2 2 3 3 1.000000 2 asc 1 1 1 1 1.000000 3 ase 1 1 1 3 0.333333 4 ase 2 2 3 3 1.000000 mmm ratio 0 1 0.555556 1 2 1.000000 Process finished with exit code 0
補充知識:python項目篇-對符合條件的某個字段進行求和,聚合函數(shù)annotate(),aggregate()函數(shù)
對符合條件的某個字段求和
需求是,計算每日的收入和
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'])
輸出結(jié)果:total_income 132
2、
from django.db.models import Sum,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'])
輸出結(jié)果:total_income 572
第二種輸出的是正確的數(shù)字
以上這篇python 實現(xiàn)分組求和與分組累加求和代碼就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
簡單了解Python下用于監(jiān)視文件系統(tǒng)的pyinotify包
這篇文章主要介紹了Python下用于監(jiān)視文件系統(tǒng)的pyinotify包,pyinotify基于inotify事件驅(qū)動機制,需要的朋友可以參考下2015-11-11Python3+Appium實現(xiàn)多臺移動設(shè)備操作的方法
這篇文章主要介紹了Python3+Appium實現(xiàn)多臺移動設(shè)備操作的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-07-07Python協(xié)程方式的實現(xiàn)及意義筆記分享
協(xié)程也被稱為微線程,是一種用戶態(tài)的上下文切換技術(shù),簡而言之,就是通過一個線程實現(xiàn)代碼互相切換執(zhí)行,本文主要給大家介紹實現(xiàn)協(xié)程的幾種方法2021-09-09