【问题标题】:Selecting the last week of each month only from a data frame - Python/Pandas仅从数据框中选择每个月的最后一周 - Python/Pandas
【发布时间】:2020-07-18 16:31:40
【问题描述】:

如果我有一个按周日期(2019 年 1 月 7 日、2019 年 1 月 14 日、2019 年 1 月 21 日...等)索引的数据框,Pandas 中有没有一种方法可以有效地仅选择索引中每个月最后一周对应的行?

【问题讨论】:

    标签: python python-3.x pandas datetime group-by


    【解决方案1】:

    只需 get 一个月的最后一天 (MonthEnd),然后进行过滤,例如(假设您的 DataFrame 中有 Date 列):

    from pandas.tseries.offsets import MonthEnd
    
    df['MonthEnd'] = df['Date'] + MonthEnd(1)
    df[ (df['MonthEnd'] - df['Date']).dt.days <= 7 ]
    

    【讨论】:

    • 我认为应该是 .dt.days 而不是 .days,但非常有帮助 - 谢谢!
    • @DalvirMandara 欢迎您!确实是这样,我是凭记忆写的:)
    猜你喜欢
    • 1970-01-01
    • 2017-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-28
    • 2012-12-20
    相关资源
    最近更新 更多