核心:
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
以上,记录本人学习过程