首页 > 解决方案 > 熊猫:分组和聚合

问题描述

我对 pandas 数据框有点陌生,目前正试图通过各州对我的数据框的总销售额来获得最高的总销售额。该数据框是关于几年来美国商店的销售情况。我想知道哪个州卖的物品最多,然后哪个州卖的最多,但是按物品的价值,所以是美元。

这是数据框的链接:https ://raw.githubusercontent.com/michalis0/DataMining_and_MachineLearning/master/data/sales.csv

这是我的代码:

# Load the data
df=pd.read_csv('https://raw.githubusercontent.com/michalis0/DataMining_and_MachineLearning/master/data/sales.csv')

# Highest demand by number of items
df["State"].value_counts()[:50]

#Highest demand by aggregated sales
df.groupby(["Customer ID","State"])["Sales"].sum()
AggSales = df.groupby("State", as_index=False)["Sales"].count()
AggSales.sort_values(by=['Sales'], inplace=True, ascending=False)
AggSales.head(50)

我的问题是,按商品数量和汇总值计算最高销售额时,我得到了相同的结果,但我不明白为什么。我尝试以许多不同的方式进行分组或聚合,但总是得到相同的结果,而且我似乎看不出哪里出错了。

标签: pythonpandasdataframedata-mining

解决方案


要计算每个国家/用户的总销售额,您需要在groupby使用sum()后添加所有销售额。count()用于计算销售出现的行数,因此它不会给我们想要的输出。

代码:

# calculate the sales of user in each country
sales_by_user_per_country = df.groupby(["Customer ID", "State"])["Sales"].sum().sort_values(
    ascending=False).reset_index()
print(sales_by_user_per_country.head(50))

# calculate the total sales in each country 
sales_by_country = df.groupby(["State"])["Sales"].sum().sort_values(ascending=False).reset_index()
print(sales_by_country.head(50))

还有其他选项可以使用方法做同样的事情pivot_table

sales_by_country = df.pivot_table(index="State",values="Sales",aggfunc="sum").sort_values("Sales",ascending=False)
print(sales_by_country.head(50))

推荐阅读