groupby是Pandas在数据分析中最常用的函数之一。它用于根据给定列中的不同值对数据点(即行)进行分组,分组后的数据可以计算生成组的聚合值。 如果我们有一个包含汽车品牌和价格信息的数据集,那么可以使用groupby功能来计算每个品牌的平均价格。 在本文中,我们将使用25个示例来详细介绍groupby函数的用法。这25个示例中还包含了一些不太常用但在各种任务中都能派上用场的操作。 这里使用的数据集是随机生成的,我们把它当作一个销售的数据集。
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、多列聚合
在一个操作中进行多个聚合。以下是我们如何计算每个商店的平均库存数量和价格。
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、对不同列的聚合进行命名
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)
找到每个店铺上个月销售排名第五的产品如下:
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函数忽略缺失值。如果用于分组的列中缺少一个值,那么它将不包含在任何组中,也不会单独显示。所以可以使用dropna参数来改变这个行为。 让我们首先添加一个缺少存储值的新行。
sales.loc[1000]=[None,"PG2",10000,120,64,96,15,53]
然后计算带有dropna参数和不带有dropna参数的每个商店的平均价格,以查看差异。
sales.groupby("store")["price"].mean() store Daisy69.327426 Rose60.513700 Violet67.808727 Name:price,dtype:float64看看设置了缺失值参数的结果:
sales.groupby("store",dropna=False)["price"].mean() store Daisy69.327426 Rose60.513700 Violet67.808727 NaN96.000000 Name:price,dtype:float64groupby函数的dropna参数,使用pandas版本1.1.0或更高版本。 19、求组的个数 有时需要知道生成了多少组,这可以使用ngroups。
sales.groupby(["store","product_group"]).ngroups 18在商店和产品组列中有18种不同值的不同组合。 20、获得一个特定分组 get_group函数可获取特定组并且返回DataFrame。 例如,我们可以获得属于存储“Daisy”和产品组“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

-
函数
+关注
关注
3文章
4331浏览量
62605 -
数据分析
+关注
关注
2文章
1449浏览量
34057 -
数据集
+关注
关注
4文章
1208浏览量
24700
原文标题:25 个例子学会 Pandas Groupby 操作!
文章出处:【微信号:DBDevs,微信公众号:数据分析与开发】欢迎添加关注!文章转载请注明出处。
发布评论请先 登录
相关推荐
为什么图腾柱电路大多数用三极管来实现的呢
为什么现在大多数四轴飞行器都采用的是X型布局
如何解决大多数电源完整性问题
大多数为单指令周期
大多数用户并不习惯在智能音箱上收听新闻
为什么大多数加密货币没有存在的必要

大多数加密数字货币都存在什么问题
大多数企业担忧5G威廉希尔官方网站 带来的网络安全风险
满足大多数倒计时控件的视图教程
为何大多数PLC采用ARM架构CPU
大多数人5G随身WiFi用户被商家引导,如何避免“劣质”随身WiFi?

评论