作用
在groupby分出的各组数据中求(多个)函数的值
参数类型
function, string, dictionary, or list of string/functions
示例
-
参数是function
import pandas as pd data = pd.DataFrame([['0902', 89, 92, 88, 90], ['0903', 91, 95, 88, 98], ['0903', 84, 81, 87, 86], ['0906', 93, 89, 99, 89], ['0902', 85, 95, 80, 87]], columns=['Date', 'score1', 'score2', 'score3', 'score4']) # 输出groupby的结果 for i, j in data.groupby('Date'): print(i, j) print('\n') # 求每一组,每个特征的最小值 print(data.groupby('Date').agg(min))
输出:
接上例,# 求每一组,每个特征的最大值 print(data.groupby('Date').agg(max)) print('\n') # 求每一组,每个特征的和 print(data.groupby('Date').agg(sum))
输出:
接上例,# 将每一组,每个特征的所有取值放在一个列表中 print(data.groupby('Date').agg(list))
输出:
同理,如果传入的函数是tuple则将结果放在一个元组中;如果传入的函数是set则将结果放在一个集合中 -
参数是string
其实就是函数名加个引号:import pandas as pd data = pd.DataFrame([['0902', 89, 92, 88, 90], ['0903', 91, 95, 88, 98], ['0903', 84, 81, 87, 86], ['0906', 93, 89, 99, 89], ['0902', 85, 95, 80, 87]], columns=['Date', 'score1', 'score2', 'score3', 'score4']) # 输出groupby的结果 for i, j in data.groupby('Date'): print(i, j) print('\n') # 求每一组,每个特征的最小值 print(data.groupby('Date').agg('min'))
输出:
和第一个例子输出结果是一样的 -
参数是dictionary
import pandas as pd data = pd.DataFrame([['0902', 89, 92, 88, 90], ['0903', 91, 95, 88, 98], ['0903', 84, 81, 87, 86], ['0906', 93, 89, 99, 89], ['0902', 85, 95, 80, 87]], columns=['Date', 'score1', 'score2', 'score3', 'score4']) # 输出groupby的结果 for i, j in data.groupby('Date'): print(i, j) print('\n') #对score1列取各组的最小值,列名还是score1 print(data.groupby(['Date']).agg({'score1': 'min'}))
输出:
接上例,# 求分组后各组数据的score2的最小值最大值 print(data.groupby(['Date']).agg({'score2': ['min', 'max']}))
输出:
-
参数是字符串列表或函数列表
大同小异,只是同时输出多个函数值import pandas as pd data = pd.DataFrame([['0902', 89, 92, 88, 90], ['0903', 91, 95, 88, 98], ['0903', 84, 81, 87, 86], ['0906', 93, 89, 99, 89], ['0902', 85, 95, 80, 87]], columns=['Date', 'score1', 'score2', 'score3', 'score4']) # 输出groupby的结果 for i, j in data.groupby('Date'): print(i, j) print('\n') # 求每一组,每个特征的最小值和最大值 print(data.groupby(['Date']).agg(['min', 'max']))
输出: