【发布时间】:2020-05-23 03:27:24
【问题描述】:
我有一个有多个 id 的表,每个表都有不同的开始日期。结束日期对所有人都将保持不变,并将从今天的日期开始动态更改为上个月的最后一天。我正在尝试遍历每个 id 和相应的开始日期,以获取从开始日期到结束日期的月份列表,映射回 id。
我当前的表格如下所示:
ID Start_Date End_Date
A 2019-12-15 2020-04-30
B 2020-03-03 2020-04-30
我想要的输出表:
ID Start_Date End_Date ID_period
A 2019-12-15 2020-04-30 201912
A 2019-12-15 2020-04-30 202001
A 2019-12-15 2020-04-30 202002
A 2019-12-15 2020-04-30 202003
A 2019-12-15 2020-04-30 202004
B 2020-03-03 2020-04-30 202003
B 2020-03-03 2020-04-30 202004
我已经尝试了以下代码,其中一些更改来自Generate list of months between interval in python
from datetime import datetime, timedelta
from collections import OrderedDict
dates = ["2014-10-10","2016-01-01"]
def monthlist_fast(dates):
for val in enumerate(dates):
start = val
end = dt.date.today().replace(day=1) - timedelta(days=1)
start, end = [datetime.strptime(_, "%Y-%m-%d") for _ in dates]
total_months = lambda dt: dt.month + 12 * dt.year
mlist = []
for tot_m in range(total_months(start)-1, total_months(end)):
y, m = divmod(tot_m, 12)
mlist.append(datetime(y, m+1, 1).strftime("%Y%m"))
return mlist
我的结果:
['201410',
'201411',
'201412',
'201501',
'201502',
'201503',
'201504',
'201505',
'201506',
'201507',
'201508',
'201509',
'201510',
'201511',
'201512',
'201601']
但我无法找到将这些映射回我的 Id 的方法,尤其是因为我的 start_dates 不断随着不同的 Id 而变化。任何帮助,将不胜感激。谢谢。
【问题讨论】:
-
您想要
python解决方案还是pyspark? -
@SMaZ 我的桌子在 pyspark 中
-
你的 spark 版本是什么?
-
@MohammadMurtazaHashmi 2.2.0.cloudera4
标签: python-3.x list dictionary pyspark