TOOLS_Pandas groupby 分组聚合常用方法使用示例
创始人
2024-05-29 16:04:37
0

TOOLS_Pandas groupby 分组聚合常用方法使用示例

  • 根据给定列中的不同值对数据点(行)进行分组;
  • 分组后的数据可以计算生成组的聚合值;

注意:下文仅是常用的一些示例,实际操作时可组合使用的方式要多得多

import pandas as pd
df = pd.read_excel("./工作簿1.xlsx")
df.head()
storeproduct_groupproduct_codestock_qtycostpricelast_week_saleslast_month_sales
0VioletPG14187498420.76569.911358
1RosePG24195473545.64712.411658
2VioletPG24204968640.42854.912288
3DaisyPG14219241869.691034.551445
4DaisyPG24718140112.5426.5950285

n列分组n特征列n聚合

# 单列分组——所有数值型特征列——单聚合
df.groupby("store").mean() # 单列分组——单特征列——单聚合
df.groupby("store")["price"].mean() # 多列分组——多特征列——多聚合
df.groupby(["store","product_group"])[["cost","price"]].agg(["mean","max"]) 
costprice
meanmaxmeanmax
storeproduct_group
DaisyPG1869.69869.691034.551034.55
PG212.5412.5426.5926.59
RosePG2545.64545.64712.41712.41
VioletPG1420.76420.76569.91569.91
PG2640.42640.42854.91854.91

对聚合结果进行命名

df.groupby("store").agg(mean_price = ("price", "mean"),max_price = ("price", "max"),mean_cost =  ("cost", "mean"),max_cost = ("cost", "max"),
)
mean_pricemax_pricemean_costmax_cost
store
Daisy530.571034.55441.115869.69
Rose712.41712.41545.640545.64
Violet712.41854.91530.590640.42

as_index 参数

  • 如果groupby输出的是DataFrame,可以使用该参数将分组的列(默认会被处理为索引列)加入到结果的DataFrame中(转换为特征列);
df.groupby("store", as_index=False).agg(mean_price = ("price", "mean"),max_price = ("price", "max"),mean_cost =  ("cost", "mean"),max_cost = ("cost", "max"),
)
storemean_pricemax_pricemean_costmax_cost
0Daisy530.571034.55441.115869.69
1Rose712.41712.41545.640545.64
2Violet712.41854.91530.590640.42

dropna 参数

groupby函数默认会忽略分组的缺省值:如果用于分组的列中缺少值,那么它将不被包含到任何组中,也不会单独显示;

使用dropna参数可以改变这一行为;

df.loc[5] = [None, "PG2", 1000,120,60,90,15,50]
df.groupby("store", dropna=False)["price"].mean()
store
Daisy     530.57
Rose      712.41
Violet    712.41
NaN        90.00
Name: price, dtype: float64

排序输出

  • 使用sort_values函数根据聚合列多输出进行排序
df.groupby("store", as_index=False).agg(mean_price = ("price", "mean"),max_price = ("price", "max"),mean_cost =  ("cost", "mean"),max_cost = ("cost", "max"),
).sort_values(by="mean_price", ascending=False)
storemean_pricemax_pricemean_costmax_cost
1Rose712.41712.41545.640545.64
2Violet712.41854.91530.590640.42
0Daisy530.571034.55441.115869.69

某一列的Top N

  • max() 取最大值
  • nlargest(N)nsmallest(N) 取前N个最值
df.groupby("store")["price"].max()
df.groupby("store")["price"].nlargest(2)
store    
Daisy   3    1034.554      26.59
Rose    1     712.41
Violet  2     854.910     569.91
Name: price, dtype: float64

第N个值

  • 先排序,再取值
df_sorted = df.sort_values(by=["store","price"], ascending=False, ignore_index=True)
# ignore_index参数,会重置索引# 找到每个分组中的第一个值(按照price倒序,对应的就是每组中price最高的一条记录)
df_sorted.groupby("store", as_index=False).nth(0)# 找到每个分组中的最后一个值(按照price倒序,对应的就是每组中price最低的一条记录)
df_sorted.groupby("store", as_index=False).nth(-1)
storeproduct_groupproduct_codestock_qtycostpricelast_week_saleslast_month_sales
1VioletPG14187498420.76569.911358
2RosePG24195473545.64712.411658
4DaisyPG24718140112.5426.5950285

唯一值、唯一值的数量

  • unique函数 查找每组中的唯一值
  • nunique函数 统计每组中唯一值的数量
df.groupby("store", as_index=False).agg(unique_val = ("product_code", "unique")
)
storeunique_val
0Daisy[4219, 4718]
1Rose[4195]
2Violet[4187, 4204]
df.groupby("store", as_index=False).agg(number_unique_val = ("product_code", "nunique")
)
storenumber_unique_val
0Daisy2
1Rose1
2Violet2

组的个数

# 两列的组合数
df.groupby(["store", "product_group"]).ngroups
5

获取特定分组

asign_pg1 = df.groupby(["store", "product_group"]
).get_group(("Daisy", "PG1"))asign_pg1
storeproduct_groupproduct_codestock_qtycostpricelast_week_saleslast_month_sales
3DaisyPG14219241869.691034.551445

Lambda

  • 在agg函数中使用lambda表达式,自定义聚合操作
df.groupby("store").agg(test_p = ("price", lambda x: round(x.sum()/1000, 1))
)
test_p
store
Daisy1.1
Rose0.7
Violet1.4

apply函数

  • 使用apply函数将Lambda表达式应用到每个组。
  • 例如,我们可以计算每家店利润值;
df.groupby("store").apply(lambda x: (x.price - x.cost).sum()
)
store
Daisy     178.91
Rose      166.77
Violet    363.64
dtype: float64

expanding 函数

import numpy as npdf = pd.DataFrame({"date": pd.date_range(start="2022-08-01", periods=8, freq="D"),"category": list("AAAABBBB"),"value": np.random.randint(10, 30, size=8)}
)
df
datecategoryvalue
02022-08-01A26
12022-08-02A25
22022-08-03A29
32022-08-04A10
42022-08-05B25
52022-08-06B18
62022-08-07B24
72022-08-08B15
# 累计总和
df["cum_sum"] = df.groupby("category")["value"].cumsum()
df
datecategoryvaluecum_sum
02022-08-01A2626
12022-08-02A2551
22022-08-03A2980
32022-08-04A1090
42022-08-05B2525
52022-08-06B1843
62022-08-07B2467
72022-08-08B1582
# expanding函数提供展开转换。但是对于展开以后的操作还是需要一个累计函数来堆区操作
df["cum_sum2"] = df.groupby("category")["value"].expanding().sum().values
df
datecategoryvaluecum_sumcum_sum2
02022-08-01A262626.0
12022-08-02A255151.0
22022-08-03A298080.0
32022-08-04A109090.0
42022-08-05B252525.0
52022-08-06B184343.0
62022-08-07B246767.0
72022-08-08B158282.0

相关内容

热门资讯

中证A500ETF摩根(560... 8月22日,截止午间收盘,中证A500ETF摩根(560530)涨1.19%,报1.106元,成交额...
A500ETF易方达(1593... 8月22日,截止午间收盘,A500ETF易方达(159361)涨1.28%,报1.104元,成交额1...
何小鹏斥资约2.5亿港元增持小... 每经记者|孙磊    每经编辑|裴健如 8月21日晚间,小鹏汽车发布公告称,公司联...
中证500ETF基金(1593... 8月22日,截止午间收盘,中证500ETF基金(159337)涨0.94%,报1.509元,成交额2...
中证A500ETF华安(159... 8月22日,截止午间收盘,中证A500ETF华安(159359)涨1.15%,报1.139元,成交额...
科创AIETF(588790)... 8月22日,截止午间收盘,科创AIETF(588790)涨4.83%,报0.760元,成交额6.98...
创业板50ETF嘉实(1593... 8月22日,截止午间收盘,创业板50ETF嘉实(159373)涨2.61%,报1.296元,成交额1...
港股异动丨航空股大幅走低 中国... 港股航空股大幅下跌,其中,中国国航跌近7%表现最弱,中国东方航空跌近5%,中国南方航空跌超3%,美兰...
电网设备ETF(159326)... 8月22日,截止午间收盘,电网设备ETF(159326)跌0.25%,报1.198元,成交额409....
红利ETF国企(530880)... 8月22日,截止午间收盘,红利ETF国企(530880)跌0.67%,报1.034元,成交额29.0...