【问题标题】:Add months to a date in Pandas在 Pandas 中为日期添加月份
【发布时间】:2018-03-26 06:27:45
【问题描述】:

我试图弄清楚如何将 3 个月添加到 Pandas 数据框中的日期,同时保持日期格式,以便我可以使用它来查找范围。

这是我尝试过的:

#create dataframe
df = pd.DataFrame([pd.Timestamp('20161011'),
                   pd.Timestamp('20161101') ], columns=['date'])

#create a future month period
plus_month_period = 3

#calculate date + future period
df['future_date'] = plus_month_period.astype("timedelta64[M]")

但是,我收到以下错误:

AttributeError: 'int' object has no attribute 'astype'

【问题讨论】:

    标签: python pandas date


    【解决方案1】:

    你可以使用pd.DateOffset

    In [1756]: df.date + pd.DateOffset(months=plus_month_period)
    Out[1756]:
    0   2017-01-11
    1   2017-02-01
    Name: date, dtype: datetime64[ns]
    

    使用pd.offsets.MonthOffset的另一种方式

    In [1785]: df.date + pd.offsets.MonthOffset(plus_month_period)
    Out[1785]:
    0   2016-10-14
    1   2016-11-04
    Name: date, dtype: datetime64[ns]
    

    详情

    In [1757]: df
    Out[1757]:
            date
    0 2016-10-11
    1 2016-11-01
    
    In [1758]: plus_month_period
    Out[1758]: 3
    

    【讨论】:

    • pd.offsets.MonthOffset 不添加月份,如结果所示。它为我增加了几天,如图所示。
    • 一个更通用的解决方案现在是from pandas.tseries.offsets import DateOffset,然后是+ DateOffset(months=1)
    【解决方案2】:

    假设您有一个以下格式的数据框,您必须将整数月份添加到日期列中。

    Start_Date Months_to_add
    2014-06-01 23
    2014-06-01 4
    2000-10-01 10
    2016-07-01 3
    2017-12-01 90
    2019-01-01 2

    在这种情况下,使用Zero's codemattblack's code 将没有用处。您必须在函数接受 2 个参数的行上使用 lambda 函数 -

    1. 需要添加月份的日期
    2. 整数格式的月份值

    您可以使用以下功能:

    # Importing required modules
    from dateutil.relativedelta import relativedelta
    
    # Defining the function
    def add_months(start_date, delta_period):
      end_date = start_date + relativedelta(months=delta_period)
      return end_date
    

    在此之后,您可以使用以下代码 sn-p 将月份添加到 Start_Date 列。使用Pandasprogress_apply 功能。请参阅 progress_apply 上的 Stackoverflow 答案:Progress indicator during pandas operations

    from tqdm import tqdm
    tqdm.pandas()
    
    df["End_Date"] = df.progress_apply(lambda row: add_months(row["Start_Date"], row["Months_to_add"]), axis = 1)
    

    这是完整的代码表单数据集创建,供您参考:

    import pandas as pd
    from dateutil.relativedelta import relativedelta
    from tqdm import tqdm
    tqdm.pandas()
    
    # Initilize a new dataframe
    df = pd.DataFrame()
    
    # Add Start Date column
    df["Start_Date"] = ['2014-06-01T00:00:00.000000000',
                        '2014-06-01T00:00:00.000000000',
                        '2000-10-01T00:00:00.000000000',
                        '2016-07-01T00:00:00.000000000',
                        '2017-12-01T00:00:00.000000000',
                        '2019-01-01T00:00:00.000000000']
    
    # To convert the date column to a datetime format
    df["Start_Date"] = pd.to_datetime(df["Start_Date"])
    # Add months column
    df["Months_to_add"] = [23, 4, 10, 3, 90, 2]
    
    # Defining the Add Months function
    def add_months(start_date, delta_period):
      end_date = start_date + relativedelta(months=delta_period)
      return end_date
    
    # Apply function on the dataframe using lambda operation.
    df["End_Date"] = df.progress_apply(lambda row: add_months(row["Start_Date"], row["Months_to_add"]), axis = 1)
    

    您将获得如下的最终输出数据帧。

    Start_Date Months_to_add End_Date
    2014-06-01 23 2016-05-01
    2014-06-01 4 2014-10-01
    2000-10-01 10 2001-08-01
    2016-07-01 3 2016-10-01
    2017-12-01 90 2025-06-01
    2019-01-01 2 2019-03-01

    如果上述代码有任何问题,请添加到 cmets。
    万事如意!

    【讨论】:

      猜你喜欢
      • 2021-08-08
      • 1970-01-01
      • 2019-04-02
      • 2011-08-04
      • 1970-01-01
      • 1970-01-01
      • 2017-08-10
      • 1970-01-01
      相关资源
      最近更新 更多