我将以下格式的数据存储在pandas数据框架中
PolicyNumber InceptionDate
1 2017-12-28 00:00:00.0
https://i.stack.imgur.com/pEfLT.png
我想根据起始日期将这条记录拆分为12条记录。例如,
1 2017-12-28 00:00:00.0
1 2018-1-28 00:00:00.0
1 2018-2-28 00:00:00.0
1 2018-3-28 00:00:00.0
.
.
1 2018-11-28 00:00:00.0
这可能吗?
您可以使用pd.date_range
生成日期范围列表,然后爆炸列
df['InceptionDate'] = pd.to_datetime(df['InceptionDate'])
df = (df.assign(InceptionDate=df['InceptionDate'].apply(lambda date: pd.date_range(start=date, periods=12, freq='MS')+pd.DateOffset(days=date.day-1)))
.explode('InceptionDate'))
print(df)
PolicyNumber InceptionDate
0 1 2018-01-28
0 1 2018-02-28
0 1 2018-03-28
0 1 2018-04-28
0 1 2018-05-28
0 1 2018-06-28
0 1 2018-07-28
0 1 2018-08-28
0 1 2018-09-28
0 1 2018-10-28
0 1 2018-11-28
0 1 2018-12-28
将其从日期时间类型转换为原始格式
df['InceptionDate'] = df['InceptionDate'].dt.strftime('%Y-%m-%d %H:%M:%S.%f')
PolicyNumber InceptionDate
0 1 2018-01-28 00:00:00.000000
0 1 2018-02-28 00:00:00.000000
0 1 2018-03-28 00:00:00.000000
0 1 2018-04-28 00:00:00.000000
0 1 2018-05-28 00:00:00.000000
0 1 2018-06-28 00:00:00.000000
0 1 2018-07-28 00:00:00.000000
0 1 2018-08-28 00:00:00.000000
0 1 2018-09-28 00:00:00.000000
0 1 2018-10-28 00:00:00.000000
0 1 2018-11-28 00:00:00.000000
0 1 2018-12-28 00:00:00.000000