【问题标题】:How to count products per each category and sub-category? [duplicate]如何计算每个类别和子类别的产品? [复制]
【发布时间】:2021-01-11 12:54:28
【问题描述】:

根据指定的dataframe

category_uuid   collection_uuid product_uuid
fe4eef35-3fde-4037-a6ce-e8ebd2859cd6    0020005c-55e3-47cb-9056-ed25dd5f24f0    00a1c641-2f8f-440d-b105-d89180cac625
fe4eef35-3fde-4037-a6ce-e8ebd2859cd6    0020005c-55e3-47cb-9056-ed25dd5f24f0    021bb4b1-e21e-4ba5-8856-15198585f873
fe4eef35-3fde-4037-a6ce-e8ebd2859cd6    0020005c-55e3-47cb-9056-ed25dd5f24f0    0331a74f-1e99-418e-9abc-304d269452b2

我需要计算以下聚合值:

category_uuid   collections_count   products_count
fe4eef35-3fde-4037-a6ce-e8ebd2859cd6    124 1563
...

即汇总每个类别的产品和集合的总数。

我已尝试执行以下操作:

df_products_small.groupby(['category_uuid']).agg({'collection_uuid': ['count'], ' products_count': ['count'] })

【问题讨论】:

    标签: python sql pandas aggregate data-analysis


    【解决方案1】:

    您可以使用数据透视表来做到这一点(考虑到您需要 UNIQUE 元素的数量):

    import pandas as pd:
    
    pd.pivot_table(df, index='category_uuid', values=['collections_uuid', 'products_uuid'], aggfunc=lambda x: len(x.unique()))
    

    【讨论】:

    • 谢谢!您的解决方案在我的情况下效果很好。
    猜你喜欢
    • 2011-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-04
    • 2013-05-28
    • 1970-01-01
    相关资源
    最近更新 更多