博客 / 詳情

返回

Pandas GroupBy 的 10 個實用技巧

很多人把 groupby 理解成單純的求和、計數這類操作,比如説算算總收入、數數用户量,然後就沒了。實際上它的應用場景要廣得多:計算組內特徵、數據標準化、構造滾動指標、合併不同維度的統計結果,甚至處理一些複雜的嵌套數據結構。

所以本文將介紹10個實際工作中比較有用的技巧,文章的代碼都是可以直接拿來用。

1、一次性應用多個聚合函數

 import pandas as pd  

df = pd.DataFrame({  
    "team": ["A", "A", "B", "B"],  
    "score": [10, 15, 7, 20]  
})  
result = df.groupby("team").agg({  
    "score": ["sum", "mean", "max"]  
})  
print(result)
####
    score               
            sum  mean  max  
    team                      
    A        25  12.5   15  
     B        27  13.5   20

2、聚合後對結果進行命名

 result = df.groupby("team").agg(  
    total_score=("score", "sum"),  
    avg_score=("score", "mean"),  
    max_score=("score", "max")  
)  

print(result)
###
    total_score  avg_score  max_score  
    team                                      
    A              25       12.5         15  
     B              27       13.5         20  

3、transform

 df["team_avg"] = df.groupby("team")["score"].transform("mean")  
 print(df)

每一行現在都帶上了所屬組的均值,這在特徵工程裏特別常用。

     team  score  team_avg  
     0    A     10      12.5  
     1    A     15      12.5  
     2    B      7      13.5  
     3    B     20      13.5

4、組內累積計算

 df["cumulative_score"] = (  
     df.groupby("team")["score"]  
       .transform(lambda s: s.cumsum())  
 )  
   
 print(df)

累積和會在每個分組內部重新開始計算。

 team  score  team_avg  cumulative_score  
     0    A     10      12.5                10  
     1    A     15      12.5                25  
     2    B      7      13.5                 7  
     3    B     20      13.5                27

5、自定義聚合邏輯

 defscore_range(s):  
     returns.max() -s.min()  
   
 result=df.groupby("team")["score"].agg(score_range)  
 print(result)

一些複雜的業務指標基本都可以用這種方式實現。

     team  
     A     5  
     B    13  
     Name: score, dtype: int64

6、統計唯一值

 df2=pd.DataFrame({  
    "team": ["A", "A", "B", "B", "B"],  
    "member": ["x", "y", "x", "x", "z"]  
})  

unique_counts=df2.groupby("team")["member"].nunique()  
unique_sets=df2.groupby("team")["member"].apply(set)  

print(unique_counts)  
print(unique_sets)

####
    team  
    A    2  
    B    2  
    Name: member, dtype: int64  

    
   team  
   A       {x, y}  
   B    {x, z}  
   Name: member, dtype: object

7、按類別分組的正確姿勢

 df2["team"] = df2["team"].astype("category")  
   
 result = df2.groupby("team", observed=False)["member"].count()  
 print(result)

做報表的時候有些預定義的類別即使沒數據也需要顯示出來,這時候這個參數就派上用場了。

     team  
     A    2  
     B    3  
     Name: member, dtype: int64

8、多層級分組

 df3 = pd.DataFrame({  
    "team": ["A", "A", "B", "B"],  
    "year": [2023, 2024, 2023, 2024],  
    "score": [10, 15, 7, 20]  
})  

result = df3.groupby(["team", "year"])["score"].sum()  
 print(result)

隊列分析或者按時間切片的場景基本就是這個結構。

  team  year  
     A     2023    10  
           2024    15  
     B     2023     7  
           2024    20  
     Name: score, dtype: int64

9、扁平化輸出

 flat = df3.groupby("team", as_index=False).agg({"score": "sum"})  
 print(flat)

對接 API 或者導入 BI 工具時,扁平結構往往更方便。

      team  score  
     0    A     25  
     1    B     27

10、結合透視表使用

 pivot = pd.pivot_table(  
    df3,  
    values="score",  
    index="team",  
    columns="year",  
    aggfunc="sum"  
)  

 print(pivot)

這種交叉統計的表格在做彙總分析時經常用到。

     year  2023  2024  
     team                
     A       10    15  
     B        7    20

總結

groupby 的功能遠比表面看起來豐富。agg 處理多指標彙總,transform 生成組級特徵,MultiIndex 分組配合 pivot_table 可以快速構建複雜的數據視圖。熟練掌握這些用法之後,很多數據處理任務的代碼量能減少不少。

多指標統計用 agg,命名聚合讓代碼更清晰,組內特徵計算靠 transform,業務邏輯封裝成自定義函數,多維度報表用 MultiIndex 和透視表組合。
[
https://avoid.overfit.cn/post/da6bdf53716948b7bd26eddc31ea94a4](https://avoid.overfit.cn/post/da6bdf53716948b7bd26eddc31ea94a4)

user avatar
0 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.