首页 > 解决方案 > 熊猫中的 GroupBy 不使用聚合函数

问题描述

我正在研究零售数据存储并尝试获取类别和子类别的报告。我尝试查看 stackoverflow 的答案,但找不到解决方案。

以下是样本数据(不是完整的数据集)

+-----------------+--------------+
|    Category     | Sub-Category |
+-----------------+--------------+
| Furniture       | Bookcases    |
| Furniture       | Chairs       |
| Office Supplies | Labels       |
| Furniture       | Tables       |
| Office Supplies | Storage      |
| Furniture       | Furnishings  |
+-----------------+--------------+

我的代码:

orders[['Category', 'Sub-Category']].groupby(by=['Category', 'Sub-Category']).nunique()

我的结果集:

                              Category  Sub-Category
Category        Sub-Category                        
Furniture       Bookcases            1             1
                Chairs               1             1
                Furnishings          1             1
                Tables               1             1
Office Supplies Appliances           1             1
                Art                  1             1

我想要的只是

    Category        Sub-Category                        

    Furniture       Bookcases       
                    Chairs            
                    Furnishings  
                    Tables    
    Office Supplies Appliances       
                    Art    

有没有办法可以隐藏计数。如果我不包括,nunique那么我将返回对象而不是实际输出。

我不确定熊猫中是否存在此功能,或者我应该看看其他东西。

标签: pythonpython-3.xpandas

解决方案


使用

df=df.sort_values('Category')
df.Category=df.Category.mask(df.Category.duplicated(),'')
df
Out[450]: 
         Category Sub-Category
0       Furniture    Bookcases
1                       Chairs
3                       Tables
5                  Furnishings
2  OfficeSupplies       Labels
4                      Storage

推荐阅读