熊猫:分组和聚合

Panda : Group by and Aggregate

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

这是数据框的 link :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)

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

要计算每个 country/user 的总销售额,您需要在 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))