【问题标题】:Pandas Group by TimeGrouperTimeGrouper 的 Pandas 组
【发布时间】:2017-06-28 16:45:45
【问题描述】:

我想按月对数据进行分组,选择每个月的最后一行。

数据:

>>> df
Date
1985-10-14    46.50
1985-10-23    47.50
1985-10-24    46.88
1985-11-21    50.25
1985-11-22    50.38
1985-11-25    50.38
>>> df.groupby(pd.TimeGrouper('M')).nth(-1)
Date
1985-10-31    46.88
1985-11-30    50.38

预期结果:

1985-10-24    46.88
1985-11-25    50.38

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    我认为您需要先从DatetimeIndexreset_index 创建列,然后使用resampleResampler.last,最后删除index

    print (df)
                  col
    Date             
    1985-10-14  46.50
    1985-10-23  47.50
    1985-10-24  46.88
    1985-11-21  50.25
    1985-11-22  50.38
    1985-11-25  50.38
    
    
    df = df.reset_index().resample('M', on='Date').last().reset_index(drop=True)
    print (df)
            Date    col
    0 1985-10-24  46.88
    1 1985-11-25  50.38
    

    对于旧版本,从索引创建列:

    df = df.assign(Date=df.index).resample('M').last().reset_index(drop=True)
    print (df)
         col       Date
    0  46.88 1985-10-24
    1  50.38 1985-11-25
    

    df['Date'] = df.index
    df = df.resample('M').last().reset_index(drop=True)
    print (df)
         col       Date
    0  46.88 1985-10-24
    1  50.38 1985-11-25
    

    【讨论】:

    • 重新采样中的参数在 0.19 版本的熊猫中如果我使用 0.18 会怎样
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-28
    • 1970-01-01
    • 2017-08-16
    • 2017-05-19
    • 1970-01-01
    • 2020-02-04
    • 1970-01-01
    相关资源
    最近更新 更多