groupby常用方法

核心:

1.不论分组键是数组、列表、字典、Series、函数,只要其与待分组变量的轴长度一致都可以传入groupby进行分组。

2.默认axis=0按行分组,可指定axis=1对列分组

 

1.根据表本身的某一列或多列内容进行分组聚合

1.1按照一列进行聚合

import numpy as np
import pandas as pd
from pandas import DataFrame
 
a_data=pd.DataFrame({"a_char":list("abab"),
        "number":[1,1,2,2],
        "subject":["maths","science","chem","history"],
        "score":[100,90,80,90]})
a_data.index=["A","B","C","D"]
print(a_data)
"""
  a_char  number  subject  score
A      a       1    maths    100
B      b       1  science     90
C      a       2     chem     80
D      b       2  history     90
"""
groups=a_data.groupby("a_char")
for name,group in groups:
    print(name)
    print(group)
    print("=========")
"""
输出为:
a
  a_char  number subject  score
A      a       1   maths    100
C      a       2    chem     80
=========
b
  a_char  number  subject  score
B      b       1  science     90
D      b       2  history     90
=========
"""

1.2按照多列进行聚合(多列之间维度的笛卡尔积)

groups=a_data.groupby(["a_char","number"])
for name,group in groups:
    print(name)
    print(group)
    print("=========")
"""
输出为:
('a', 1)
  a_char  number subject  score
A      a       1   maths    100
=========
('a', 2)
  a_char  number subject  score
C      a       2    chem     80
=========
('b', 1)
  a_char  number  subject  score
B      b       1  science     90
=========
('b', 2)
  a_char  number  subject  score
D      b       2  history     90
=========
"""

2.按列进行聚合

a_dict={"number":"int","score":"int","a_char":"char","subject":"char"}
groups=a_data.groupby(a_dict,axis=1)
for name,group in groups:
    print(name)
    print(group)
    print("=====")
"""
char
  a_char  subject
A      a    maths
B      b  science
C      a     chem
D      b  history
=====
int
   number  score
A       1    100
B       1     90
C       2     80
D       2     90
=====

既然我们可以通过传入字典来对列进行分组,那么肯定也可以通过传入Series来对列进行分组了(Series中的index就相当字典中的key嘛):

a_series=Series(a_dict)
groups=a_data.groupby(a_series,axis=1)
for name,group in groups:
    print(name)
    print(group)
    print("=====")
"""
char
  a_char  subject
A      a    maths
B      b  science
C      a     chem
D      b  history
=====
int
   number  score
A       1    100
B       1     90
C       2     80
D       2

参考:https://www.cnblogs.com/zhangzhangwhu/p/7219651.html

以上,记录本人学习过程

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值