Pandas中的多SELECT COUNT(不同)

时间:2017-10-23 14:53:03

标签: python group-by count distinct pandas-groupby

在SQL中:

SELECT distinct user_id
    , COUNT(product_id) AS c_products
    , COUNT(distinct product_id) AS c_distinct_product
FROM tables
GROUP BY user_id

我怎么能在熊猫中做到这一点?

1 个答案:

答案 0 :(得分:0)

轻松:

df.groupby('user_id').agg({'product_id': ['count', pd.Series.nunique]})

Pandas拥有帮助从SQL到Pandas的翻译的文档:https://pandas.pydata.org/pandas-docs/stable/comparison_with_sql.html