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

如何将groupby输出转换为含多列的DataFrame?基于Northwind数据库

解决分组后DataFrame仅含聚合列的问题

嘿,这个问题我之前也碰到过!原因很简单:你调用groupby()时指定的productID、categoryID、categoryName这三个列,默认会变成DataFrame的行索引,而非普通数据列,所以shape才会显示只有1列(也就是你的聚合结果no_orders)。

有两种非常直接的解决方式,选哪种都可以:

方法1:分组时直接保留列为数据列

在groupby()里添加as_index=False参数,这样分组列就不会被转成索引,聚合后直接得到包含4列的DataFrame:

popularity_products = order_details_products_categories.groupby(
    ['productID', 'categoryID', 'categoryName'],
    as_index=False  # 关键参数:让分组列保持为普通列
).agg(no_orders=('productID', 'count'))
popularity_products.sort_values(by='no_orders', ascending=False, inplace=True)

方法2:对已有结果重置索引

如果你已经完成了分组聚合操作,不想重新跑代码,可以直接对现有的popularity_products调用reset_index(),把索引列转成普通数据列:

popularity_products = popularity_products.reset_index()

执行完这行代码后,你再查看popularity_products.shape,就会得到(77, 4),刚好包含你需要的productID、categoryID、categoryName和no_orders这四列。

小补充:如果你的pandas版本比较新(1.1.0及以上),也可以把reset_index()链式调用在聚合之后,比如:

popularity_products = order_details_products_categories.groupby(
    ['productID', 'categoryID', 'categoryName']
).agg(no_orders=('productID', 'count')).reset_index()

效果和方法1是完全一致的~

内容的提问来源于stack exchange,提问作者Hendrra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 16:07:50