在Pandas中添加几个月的日期

mat*_*ack 17 python date pandas

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

这就是我尝试过的:

#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]")
Run Code Online (Sandbox Code Playgroud)

但是,我收到以下错误:

AttributeError: 'int' object has no attribute 'astype'
Run Code Online (Sandbox Code Playgroud)

关于如何做到这一点的任何想法?谢谢!

Zer*_*ero 31

你可以用 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]
Run Code Online (Sandbox Code Playgroud)

另一种方式使用 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]
Run Code Online (Sandbox Code Playgroud)

细节

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

In [1758]: plus_month_period
Out[1758]: 3
Run Code Online (Sandbox Code Playgroud)

  • 现在更通用的解决方案是“from pandas.tseries.offsets import DateOffset”,然后是“+ DateOffset(months=1)” (8认同)

小智 11

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

开始日期 待添加月数
2014-06-01 23
2014-06-01 4
2000年10月1日 10
2016-07-01 3
2017-12-01 90
2019-01-01 2

在这种情况下,使用Zero 的代码Mattblack 的代码将没有用处。您必须在函数采用 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
Run Code Online (Sandbox Code Playgroud)

之后,您可以使用以下代码片段向Start_Date列添加月份。使用Pandasprogress_apply的功能。请参阅 Stackoverflow 上的答案:Progress Indicator during pandas Operationsprogress_apply

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)
Run Code Online (Sandbox Code Playgroud)

以下是数据集创建的完整代码,供您参考:

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)
Run Code Online (Sandbox Code Playgroud)

您将获得最终的输出数据框,如下所示。

开始日期 待添加月数 结束日期
2014-06-01 23 2016-05-01
2014-06-01 4 2014-10-01
2000年10月1日 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

以上代码如有问题请在评论中补充。
一切顺利!


Ter*_*rry 6

我认为解决此问题的最简单、最有效(更快)的方法是将日期转换为每月周期,将结果与Months_to_addto_period(M)列的值相加,然后使用命令将数据作为日期时间检索。.dt.to_timestamp()

使用 @Aruparna Maity 创建的示例数据

开始日期 待添加月数
2014-06-01 23
2014-06-20 4
2000年10月1日 10
2016-07-05 3
2017-12-15 90
2019-01-01 2
df['End_Date'] = ((df['Start_Date'].dt.to_period('M')) + df['Months_to_add']).dt.to_timestamp()
df.head(6)
#output
    Start_Date  Months_to_add   End_Date
0   2014-06-01  23              2016-05-01
1   2014-06-20  4               2014-10-01
2   2000-10-01  10              2001-08-01
3   2016-07-05  3               2016-10-01
4   2017-12-15  90              2025-06-01
5   2019-01-01  2               2019-03-01
Run Code Online (Sandbox Code Playgroud)

如果需要确切的日期,只需重复该过程,但将期间更改为天

df['End_Date'] = ((df['End_Date'].dt.to_period('D')) + df['Start_Date'].dt.day -1).dt.to_timestamp()
#output:
    Start_Date  Months_to_add   End_Date
0   2014-06-01  23              2016-05-01
1   2014-06-20  4               2014-10-20
2   2000-10-01  10              2001-08-01
3   2016-07-05  3               2016-10-05
4   2017-12-15  90              2025-06-15
5   2019-01-01  2               2019-03-01
Run Code Online (Sandbox Code Playgroud)