groupby是Pandas在數(shù)據(jù)分析中最常用的函數(shù)之一。它用于根據(jù)給定列中的不同值對數(shù)據(jù)點(即行)進(jìn)行分組,分組后的數(shù)據(jù)可以計算生成組的聚合值。 如果我們有一個包含汽車品牌和價格信息的數(shù)據(jù)集,那么可以使用groupby功能來計算每個品牌的平均價格。 在本文中,我們將使用25個示例來詳細(xì)介紹groupby函數(shù)的用法。這25個示例中還包含了一些不太常用但在各種任務(wù)中都能派上用場的操作。 這里使用的數(shù)據(jù)集是隨機(jī)生成的,我們把它當(dāng)作一個銷售的數(shù)據(jù)集。
importpandasaspd sales=pd.read_csv("sales_data.csv") sales.head()

sales.groupby("store")["stock_qty"].mean() #輸出 store Daisy1811.861702 Rose1677.680000 Violet14622.406061 Name:stock_qty,dtype:float64
2、多列聚合
在一個操作中進(jìn)行多個聚合。以下是我們?nèi)绾斡嬎忝總€商店的平均庫存數(shù)量和價格。
sales.groupby("store")[["stock_qty","price"]].mean()sales.groupby("store")[["stock_qty","price"]].mean()

sales.groupby("store")["stock_qty"].agg(["mean","max"])

sales.groupby("store").agg( avg_stock_qty=("stock_qty","mean"), max_stock_qty=("stock_qty","max") )

sales.groupby("store")[["stock_qty","price"]].agg(["mean","max"])
6、對不同列的聚合進(jìn)行命名
sales.groupby("store").agg( avg_stock_qty=("stock_qty","mean"), avg_price=("price","mean") )

sales.groupby("store",as_index=False).agg( avg_stock_qty=("stock_qty","mean"), avg_price=("price","mean") )

sales.groupby(["store","product_group"],as_index=False).agg( avg_sales=("last_week_sales","mean") ).head()

sales.groupby(["store","product_group"],as_index=False).agg(avg_sales=("last_week_sales","mean") ).sort_values(by="avg_sales",ascending=False).head()

sales.groupby("store")["last_week_sales"].nlargest(2) store Daisy4131883 231947 Rose948883 263623 Violet9913222 3392690 Name:last_week_sales,dtype:int64
11、最小的Top N
與最大值相似,也可以求最小值
sales.groupby("store")["last_week_sales"].nsmallest(2)
12、第n個值
除上面2個以外,還可以找到一組中的第n個值。
sales_sorted=sales.sort_values(by=["store","last_month_sales"],ascending=False,ignore_index=True)
找到每個店鋪上個月銷售排名第五的產(chǎn)品如下:
sales_sorted.groupby("store").nth(4)

sales_sorted.groupby("store").nth(-2)

sales.groupby("store",as_index=False).agg( unique_values=("product_code","unique") )

sales.groupby("store",as_index=False).agg( number_of_unique_values=("product_code","nunique") )

sales.groupby("store").agg( total_sales_in_thousands=( "last_month_sales", lambdax:round(x.sum()/1000,1) ) )

sales.groupby("store").apply( lambdax:(x.last_week_sales-x.last_month_sales/4).mean() ) store Daisy5.094149 Rose5.326250 Violet8.965152 dtype:float64
18、dropna
缺省情況下,groupby函數(shù)忽略缺失值。如果用于分組的列中缺少一個值,那么它將不包含在任何組中,也不會單獨顯示。所以可以使用dropna參數(shù)來改變這個行為。 讓我們首先添加一個缺少存儲值的新行。
sales.loc[1000]=[None,"PG2",10000,120,64,96,15,53]
然后計算帶有dropna參數(shù)和不帶有dropna參數(shù)的每個商店的平均價格,以查看差異。
sales.groupby("store")["price"].mean() store Daisy69.327426 Rose60.513700 Violet67.808727 Name:price,dtype:float64看看設(shè)置了缺失值參數(shù)的結(jié)果:
sales.groupby("store",dropna=False)["price"].mean() store Daisy69.327426 Rose60.513700 Violet67.808727 NaN96.000000 Name:price,dtype:float64groupby函數(shù)的dropna參數(shù),使用pandas版本1.1.0或更高版本。 19、求組的個數(shù) 有時需要知道生成了多少組,這可以使用ngroups。
sales.groupby(["store","product_group"]).ngroups 18在商店和產(chǎn)品組列中有18種不同值的不同組合。 20、獲得一個特定分組 get_group函數(shù)可獲取特定組并且返回DataFrame。 例如,我們可以獲得屬于存儲“Daisy”和產(chǎn)品組“PG1”的行如下:
aisy_pg1=sales.groupby( ["store","product_group"]).get_group(("Daisy","PG1") ) daisy_pg1.head()

sales["rank"]=sales.groupby("store"["price"].rank( ascending=False,method="dense" ) sales.head()

importnumpyasnpdf=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["cum_sum"]=df.groupby("category")["value"].cumsum()

df["cum_sum_2"]=df.groupby( "category" )["value"].expanding().sum().values

df["cum_mean"]=df.groupby( "category" )["value"].expanding().mean().values

df["current_highest"]=df.groupby( "category" )["value"].expanding().max().values

-
函數(shù)
+關(guān)注
關(guān)注
3文章
4400瀏覽量
66361 -
數(shù)據(jù)分析
+關(guān)注
關(guān)注
2文章
1494瀏覽量
35722 -
數(shù)據(jù)集
+關(guān)注
關(guān)注
4文章
1229瀏覽量
25912
原文標(biāo)題:25 個例子學(xué)會 Pandas Groupby 操作!
文章出處:【微信號:DBDevs,微信公眾號:數(shù)據(jù)分析與開發(fā)】歡迎添加關(guān)注!文章轉(zhuǎn)載請注明出處。
發(fā)布評論請先 登錄
為什么圖騰柱電路大多數(shù)用三極管來實現(xiàn)的呢
為什么現(xiàn)在大多數(shù)四軸飛行器都采用的是X型布局
技術(shù)支持工程師面試試題大多數(shù)是什么
如何解決大多數(shù)電源完整性問題
大多數(shù)為單指令周期
麥肯錫報告稱大多數(shù)工作將被人工智能接管
大多數(shù)用戶并不習(xí)慣在智能音箱上收聽新聞
為什么大多數(shù)加密貨幣沒有存在的必要

評論