在熊猫中使用GroupBy而不使用聚合功能

时间:2019-01-25 18:34:25

标签: python python-3.x pandas

我正在从事零售数据存储,并尝试获取类别和子类别的报告。我尝试查看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,那么我将返回对象而不是实际输出。

我不确定熊猫中是否存在此功能,还是应该看看其他内容。

1 个答案:

答案 0 :(得分:2)

使用

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
相关问题