You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas按Product和City分组,获取各产品订单量最大的城市

解决方法

你已经完成了分组求和的步骤,接下来可以通过以下几种方式筛选每个Product对应销量(Quantity Ordered)最大值的City:

方式一:基于多级索引直接处理

你的p_c_df是带有Product和City多级索引的DataFrame,可通过按Product分组后使用idxmax定位最大值行:

# 获取每个Product下销量最大的行索引
max_row_indices = p_c_df.groupby(level="Product")["Quantity Ordered"].idxmax()
# 提取对应行并重置索引(让结构更直观)
final_result = p_c_df.loc[max_row_indices].reset_index()

方式二:重置索引后分组筛选

先将多级索引转为普通列,再进行分组筛选:

# 把索引转为列
p_c_df_reset = p_c_df.reset_index()
# 按Product分组,找到每组中销量最大的行
final_result = p_c_df_reset.loc[p_c_df_reset.groupby("Product")["Quantity Ordered"].idxmax()]

处理并列最大值的情况

如果存在多个City的销量同为某个Product的最大值,上面的方法只会保留第一个。要保留所有符合条件的行,可使用transform:

p_c_df_reset = p_c_df.reset_index()
# 计算每个Product对应的最大销量
product_max_qty = p_c_df_reset.groupby("Product")["Quantity Ordered"].transform("max")
# 筛选出销量等于对应Product最大销量的所有行
final_result = p_c_df_reset[p_c_df_reset["Quantity Ordered"] == product_max_qty]

内容的提问来源于stack exchange,提问作者André Lourenço

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 11:06:24