假设您有一个以下格式的数据框,您必须将整数月份添加到日期列中。
| 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 code 或mattblack's code 将没有用处。您必须在函数接受 2 个参数的行上使用 lambda 函数 -
- 需要添加月份的日期
- 整数格式的月份值
您可以使用以下功能:
# 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 列。使用Pandas 的progress_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。
万事如意!