【问题标题】:Resampling when the DateTime index is not unique and the corresponding value is the sameDateTime索引不唯一且对应值相同时重采样
【发布时间】:2017-10-09 05:15:37
【问题描述】:

我有以下df DataFrame (pandas):

           attribute
2017-01-01         a
2017-01-01         a
2017-01-05         b
2017-02-01         a
2017-02-10         a

其中第一列是非唯一的datetime 索引,我想每周计算 a 和 b 的数量。如果我尝试df.attribute.resample('W').count() 将会出现错误,因为重复的条目。

我该怎么做?

【问题讨论】:

    标签: python pandas


    【解决方案1】:
    df=df.reset_index()    
    df.groupby([df['index'].dt.week,'attribute']).count()
    Out[292]: 
                     index
    index attribute       
    1     b              1
    5     a              1
    6     a              1
    52    a              2
    

    或者

    df.groupby([df.index.get_level_values(0).week,'attribute'])['attribute'].count()
    
    Out[303]: 
        attribute
    1   b            1
    5   a            1
    6   a            1
    52  a            2
    Name: attribute, dtype: int64
    

    【讨论】:

    • 很有趣,但你确定这给出了正确的答案吗?
    • 我认为 OP 希望每周重新采样,而不是仅仅提取一周并与之相关的计数。不过,你有我的赞成票。 ;-)
    • 感谢您的回答,尽管我对每周重新采样更感兴趣。
    • @thanasissdr 好极了,至少我知道你需要什么~ :)
    【解决方案2】:

    您可能对涉及groupby 后跟resample 的两步流程感兴趣。

    df.groupby(level=0).count().resample('W').sum()
                attribute
    2017-01-01        2.0
    2017-01-08        1.0
    2017-01-15        NaN
    2017-01-22        NaN
    2017-01-29        NaN
    2017-02-05        1.0
    2017-02-12        1.0
    

    【讨论】:

    • 谢谢!这就是我一直在寻找的。​​span>
    【解决方案3】:

    您可以使用pd.Grouper 按每周频率对索引进行分组:

    In [83]: df.groupby(pd.Grouper(freq='W')).count()
    Out[83]: 
                attribute
    2017-01-01          2
    2017-01-08          1
    2017-01-15          0
    2017-01-22          0
    2017-01-29          0
    2017-02-05          1
    2017-02-12          1
    

    按周频率和您可以使用的attribute 列进行分组:

    In [87]: df.groupby([pd.Grouper(freq='W'), 'attribute']).size()
    Out[87]: 
                attribute
    2017-01-01  a            2
    2017-01-08  b            1
    2017-02-05  a            1
    2017-02-12  a            1
    dtype: int64
    

    pd.Grouper 也有一个key 参数,允许您按位于列中而不是索引中的日期时间进行分组。

    【讨论】:

    • 太棒了!这似乎也很有用!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    • 2021-07-22
    • 2013-03-15
    • 1970-01-01
    • 2018-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多