前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python 实现分组求和与分组累加求和代码

python 实现分组求和与分组累加求和代码

作者头像
砸漏
发布2020-11-02 11:18:21
3.2K0
发布2020-11-02 11:18:21
举报
文章被收录于专栏:恩蓝脚本恩蓝脚本

我就废话不多说了,大家还是直接看代码吧!

代码语言:javascript
复制
# -*- 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)

运行:

代码语言:javascript
复制
 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项目篇-对符合条件的某个字段进行求和,聚合函数annotate(),aggregate()函数

对符合条件的某个字段求和

需求是,计算每日的收入和

1、

代码语言:javascript
复制
 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_income 132

2、

代码语言:javascript
复制
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'])

输出结果:total_income 572

第二种输出的是正确的数字

以上这篇python 实现分组求和与分组累加求和代码就是小编分享给大家的全部内容了,希望能给大家一个参考。

本文参与?腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-09-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客?前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与?腾讯云自媒体同步曝光计划? ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
http://www.vxiaotou.com