【问题标题】:Filter , group by and count in pandas?在熊猫中过滤、分组和计数?
【发布时间】:2019-01-13 15:07:48
【问题描述】:

TSV 文件包含一些用户事件数据:

user_uid category event_type
"11"      "like"   "post"
"33"      "share"  "status"
"11"      "like"   "post"
"42"      "share"  "post"

获取每个类别和每个 user_id 的 post 事件数量的最佳方法是什么?

我们应该显示以下输出:

user_uid category count
"11"     "like"    2
"42"     "share"   1

【问题讨论】:

    标签: python python-3.x pandas dataset


    【解决方案1】:

    清理所有尾随空格,以便正确分组。过滤你的DataFrame,然后申请groupby + size

    df['category'] = df.category.str.strip()
    df['user_uid'] = df.user_uid.str.strip()
    df[df.event_type == 'post'].groupby(['user_uid', 'category']).size()
    

    输出:

    user_uid  category
    11        like        2
    42        share       1
    dtype: int64
    

    【讨论】:

    • 你试过了吗?因为结果不是你在答案中写的。
    • @AhmedGamal 是的,df = pd.read_clipboard() 后跟我的代码给了我答案。你的答案有何不同?
    • 解决方案应该按预期工作。很好奇所以自己尝试了一下,它确实给出了预期的结果df=pd.DataFrame({'user_uid':['11','22','11','42'],'category':["like","share","like","share"],'event_type':["post","status","post","post"]}) df[df.event_type == 'post'].groupby(['user_uid', 'category']).size()
    • @AhmedGamal 我不确定unique 的输出如何,因为根据定义必须对数组进行重复数据删除,并且这些值看起来是重复的。但是您似乎对周围的空白有疑问。为 categoryuser_id 变量尝试 df['category'] = df.category.str.strip()
    • 我知道了,我认为类别有一些空格,现在可以使用
    猜你喜欢
    • 2017-11-30
    • 2018-04-29
    • 2017-03-21
    • 2021-08-20
    • 2020-01-13
    • 2021-07-06
    • 1970-01-01
    相关资源
    最近更新 更多