【问题标题】:How to get first day of each month in datetimeindex, when month doesn't starts with 01?当月份不是以 01 开头时,如何在 datetimeindex 中获取每个月的第一天?
【发布时间】:2020-06-11 08:52:17
【问题描述】:

我有一个带有 DateTimeIndex 的 DataFrame,10 年来,日复一日。我需要提取对应于每个月的第一天的行。然而,并非所有月份都以 01 开头,有些月份以 02、03、04 等开头。

2020-01-02
2020-01-03
...
2020-01-31
2020-02-03
...
2020-02-29
2020-03-02

预期的 df 必须是:

2020-01-02
2020-02-03
2020-03-02

有什么建议吗?

【问题讨论】:

    标签: python pandas datetimeindex


    【解决方案1】:

    您可以像这样从日期中提取月份:

    df["d"] = pd.to_datetime(df.d)
    df["month"] = df.d.dt.month
    
    df
               d  month
    0 2020-01-02      1
    1 2020-01-03      1
    2 2020-01-31      1
    3 2020-02-03      2
    4 2020-02-29      2
    5 2020-03-02      3
    

    然后按月分组,取组的第一个元素:

    df.groupby("month").first()
    
                   d
    month           
    1     2020-01-02
    2     2020-02-03
    3     2020-03-02
    

    【讨论】:

    • .first() 是清晰而优雅的解决方案,谢谢
    【解决方案2】:

    DatetimeIndex.to_period 用于几个月的时间段,然后通过Index.duplicated 测试重复项,并在月份的第一天使用倒置掩码过滤boolean indexing

    #if necessary
    df = df.sort_index()
    
    print (df)
                A
    date         
    2020-01-02  4
    2020-01-03  9
    2020-01-31  2
    2020-02-03  7
    2020-02-29  3
    2020-03-02  1
    
    df1 = df[~df.index.to_period('m').duplicated()]
    print (df1)
                A
    date         
    2020-01-02  4
    2020-02-03  7
    2020-03-02  1
    

    详情

    print (df.index.to_period('m'))
    PeriodIndex(['2020-01', '2020-01', '2020-01', '2020-02', '2020-02', '2020-03'], 
                dtype='period[M]', name='date', freq='M')
    
    print (df.index.to_period('m').duplicated())
    [False  True  True False  True False]
    
    print (~df.index.to_period('m').duplicated())
    [ True False False  True False  True]
    

    另一种解决方案是使用GroupBy.head:

    df1 = df.groupby(df.index.to_period('m')).head(1)
    print (df1)
                A
    date         
    2020-01-02  4
    2020-02-03  7
    2020-03-02  1
    

    【讨论】:

    • 如果我得到AttributeError: 'Index' object has no attribute 'to_period',我做错了什么?
    • @ker_laeda86 - 没有datetimeIndex,所以需要df.index = pd.to_datetime(df.index)
    • @ker_laeda86 - 如果date 是列使用df['date'] = pd.to_datetime(df['date']) 然后df[~df['date'].dt.to_period('m').duplicated()]
    猜你喜欢
    • 1970-01-01
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-29
    • 1970-01-01
    • 1970-01-01
    • 2020-07-26
    相关资源
    最近更新 更多