pandas 总计数不同

编程入门 行业动态 更新时间:2024-10-25 07:28:30
本文介绍了 pandas 总计数不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我有一个用户活动日志,我想生成一个总持续时间和每天唯一身份用户数量的报告.

Let's say I have a log of user activity and I want to generate a report of total duration and the number of unique users per day.

import numpy as np import pandas as pd df = pd.DataFrame({'date': ['2013-04-01','2013-04-01','2013-04-01','2013-04-02', '2013-04-02'], 'user_id': ['0001', '0001', '0002', '0002', '0002'], 'duration': [30, 15, 20, 15, 30]})

汇总持续时间非常简单:

Aggregating duration is pretty straightforward:

group = df.groupby('date') agg = group.aggregate({'duration': np.sum}) agg duration date 2013-04-01 65 2013-04-02 45

我想做的是对持续时间求和并同时计算不重复次数,但我似乎找不到count_distinct的等效项:

What I'd like to do is sum the duration and count distincts at the same time, but I can't seem to find an equivalent for count_distinct:

agg = group.aggregate({ 'duration': np.sum, 'user_id': count_distinct})

这有效,但是肯定有更好的方法,不是吗?

This works, but surely there's a better way, no?

group = df.groupby('date') agg = group.aggregate({'duration': np.sum}) agg['uv'] = df.groupby('date').user_id.nunique() agg duration uv date 2013-04-01 65 2 2013-04-02 45 1

我在想,我只需要提供一个将Series对象的不同项目的计数返回到聚合函数的函数,但是我对各种库的了解并不多.另外,似乎groupby对象已经知道了这些信息,所以我不是要重复努力吗?

I'm thinking I just need to provide a function that returns the count of distinct items of a Series object to the aggregate function, but I don't have a lot of exposure to the various libraries at my disposal. Also, it seems that the groupby object already knows this information, so wouldn't I just be duplicating effort?

推荐答案

其中一个怎么样?

>>> df date duration user_id 0 2013-04-01 30 0001 1 2013-04-01 15 0001 2 2013-04-01 20 0002 3 2013-04-02 15 0002 4 2013-04-02 30 0002 >>> df.groupby("date").agg({"duration": np.sum, "user_id": pd.Series.nunique}) duration user_id date 2013-04-01 65 2 2013-04-02 45 1 >>> df.groupby("date").agg({"duration": np.sum, "user_id": lambda x: x.nunique()}) duration user_id date 2013-04-01 65 2 2013-04-02 45 1

更多推荐

pandas 总计数不同

本文发布于:2023-10-31 07:48:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545483.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:pandas

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!