【问题标题】:Group by to create unique values appearing by date, as well as non-unique values by dateGroup by 以创建按日期显示的唯一值,以及按日期显示的非唯一值
【发布时间】:2016-03-30 13:48:55
【问题描述】:

我有一个看起来像这样的数据框:

    app_id   subproduct date    
0    23        3        2015-05-29
1    23        4        2015-05-29     
2    25        5        2015-05-29
3    23        3        2015-05-29
4    24        7        2015-05-29
....

我跑:

groupings =insightevents.groupby([insightevents['created_at_date'].dt.year,\
            insightevents['created_at_date'].dt.month,\
                        insightevents['created_at_date'].dt.week,insightevents['created_at_date'].dt.day,
            insightevents['created_at_date'].dt.dayofweek]);

inboxinsights=pd.DataFrame([groupings['app_id'].unique(),groupings['subproduct'].unique()]).transpose()

这给了我:

                    app_id    subproduct
2015 5 22 29 4     [23,24,25]  [3,4,5,7]

但是,我实际上想要的不仅仅是获取唯一值,而是总体上只是 app_ids 和 sub_product 在当天作为附加列加载,所以:

               unique_ app_id  unique_subproduct subproduct app_id
2015 5 22 29 4     [23,24,25]  [3,4,5,7]         [3,3,4,5,7] [23,23,23,24,25]  

我发现只是这样做:

inboxinsights=pd.DataFrame([groupings['app_id'].unique(), groupings['subproduct'].unique(),groupings['app_id'],groupings['subproduct']]).transpose()

不起作用,只是给我:

AttributeError: 'Series' object has no attribute 'type'

【问题讨论】:

    标签: python pandas unique grouping


    【解决方案1】:

    如果您只需要唯一值的数量,那很简单:

    inboxinsights.groupby('date').agg({'app_id': 'nunique', 'subproduct': 'nunique'})

    返回:

    但看起来你想要那些实际上是什么的列表。我发现this other SO question 很有帮助:

    not_unique_inboxinsights = groupby('date').agg(lambda x: tuple(x))

    然后你说想要独特的和不独特的。为此,我会制作两个 groupby 数据框并将它们连接起来,如下所示:

    unique_inboxinsights = groupby('date').agg(lambda x: set(tuple(x)))

    希望对您有所帮助。

    【讨论】:

    • 只是澄清一下,我理解的 set 方法创建了一组无序的独特项目。我的数据框中的输出不是{3,4,5,7 },而是set([3, 4,5,7])。这是预期的吗?
    • 那些是一样的。 ipython notebook 只是以不同的方式显示。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-14
    • 2014-05-17
    • 2013-01-06
    • 1970-01-01
    • 1970-01-01
    • 2012-10-02
    • 1970-01-01
    相关资源
    最近更新 更多