python - 熊猫:分组和聚合
问题描述
我对 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)
我的问题是,按商品数量和汇总值计算最高销售额时,我得到了相同的结果,但我不明白为什么。我尝试以许多不同的方式进行分组或聚合,但总是得到相同的结果,而且我似乎看不出哪里出错了。
解决方案
要计算每个国家/用户的总销售额,您需要在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))
推荐阅读
- c++ - 'for循环'在3次迭代后退出
- c# - "System.Net.Mail.SmtpException" Asp.NET
- excel - Excel Vba - 选择命名范围的行
- swift - 如何在 MacOS 上使用 Swift 中的自动布局使视图在 x 轴上居中?
- php - SIMpleXML 单独的值
- dart - 使用 final/const 而不是 var 如何更有效?
- java - Java Spring中的帮助类
- javascript - 无法将字符串转换为数字
- python-3.x - 当纸张本身有印刷的角/线时,如何找到纸张的角?
- docker - docker-compose 中的端口冲突