首页 文章

熊猫:重新采样后计算唯一值

提问于
浏览
5

我刚刚开始使用Pandas并尝试组合:按日期对数据进行分组,并计算每组中的唯一值 .

这是我的数据:

User, Type
Datetime
2014-04-15 11:00:00, A, New
2014-04-15 12:00:00, B, Returning
2014-04-15 13:00:00, C, New
2014-04-20 14:00:00, D, New
2014-04-20 15:00:00, B, Returning
2014-04-20 16:00:00, B, Returning
2014-04-20 17:00:00, D, Returning

这就是我想要达到的目的:将日期时间索引重新采样到当天(我可以做),并计算每天的唯一用户 . 我对“类型”专栏并不感兴趣 .

Day, Unique Users
2014-04-15, 3
2014-04-20, 2

我正在尝试 df.user.resample('D', how='count').unique 但它似乎没有给我正确的答案 .

2 回答

  • -1

    您无需进行重新取样即可在问题中获得所需的输出 . 我想你可以在 groupby 日期前完成:

    print df.groupby(df.index.date)['User'].nunique()
    
    2014-04-15    3
    2014-04-20    2
    dtype: int64
    

    然后,如果您愿意,您可以重新计算以在计算唯一身份用户后填写时间序列差距:

    cnt = df.groupby(df.index.date)['User'].nunique()
    cnt.index = cnt.index.to_datetime()
    print cnt.resample('D')
    
    2014-04-15     3
    2014-04-16   NaN
    2014-04-17   NaN
    2014-04-18   NaN
    2014-04-19   NaN
    2014-04-20     2
    Freq: D, dtype: float64
    
  • 5

    我遇到了同样的问题 . Karl D的答案适用于某种重新索引 - 例如,日期 . 但是如果你想要索引怎么办?

    Jan 2014
    Feb 2014
    March 2014
    

    然后将其绘制为时间序列?

    这是我做的:

    df.user.resample('M',lambda x: x.nunique())
    

相关问题