Pyspark 如何在spark中创建日期范围映射?
我有一个具有以下结构的spark数据帧Pyspark 如何在spark中创建日期范围映射?,pyspark,apache-spark-sql,pyspark-dataframes,Pyspark,Apache Spark Sql,Pyspark Dataframes,我有一个具有以下结构的spark数据帧 +-------+-------------------+ |country| date_published| +-------+-------------------+ | UK|2020-04-15 00:00:00| | UK|2020-04-14 00:00:00| | UK|2020-04-09 00:00:00| | UK|2020-04-08 00:00:00| | UK|2020-04-07
+-------+-------------------+
|country| date_published|
+-------+-------------------+
| UK|2020-04-15 00:00:00|
| UK|2020-04-14 00:00:00|
| UK|2020-04-09 00:00:00|
| UK|2020-04-08 00:00:00|
| UK|2020-04-07 00:00:00|
| UK|2020-04-06 00:00:00|
| UK|2020-04-03 00:00:00|
| UK|2020-04-02 00:00:00|
| UK|2020-04-01 00:00:00|
| UK|2020-03-31 00:00:00|
| UK|2020-03-30 00:00:00|
| UK|2020-03-27 00:00:00|
| UK|2020-03-26 00:00:00|
| UK|2020-03-25 00:00:00|
| UK|2020-03-24 00:00:00|
| UK|2020-03-23 00:00:00|
| UK|2020-03-20 00:00:00|
| UK|2020-03-19 00:00:00|
| UK|2020-03-18 00:00:00|
| UK|2020-03-17 00:00:00|
+-------+-------------------+
我想基于此数据创建一个日期映射。条件,
截止2020-01-01的所有日期应映射为年初至今
2019-04-2015年之前的所有日期应映射为最后一年
从2019-01-01到2019-04-15的所有日期应映射为截至日期的上一年年初至今
2019-04-15年之前的所有日期应映射为年前1年
我们可以创建两个列,如ytd_mapcondition 1、3、last_year_mapcondition 2、4
名单上可能还有其他国家,上述条件应该对它们有效
我尝试过的方法是创建一个数据框,其中包含每个国家发布的max_date_,但我不确定如何分别过滤每个国家的数据框
df_data = df_data_cleaned.select("date_published","country").distinct().orderBy(F.desc("date_published"))
df_max_dt = df_data.groupBy("country").agg(F.max(F.col("date_published")))
df_max_dt.collect()
我试过了,现在还在工作
spark.sql("select country,\
date_published,\
(case when date_published >= max_date_published_last_year then 'LAST_1_YEAR'\
when date_published <= max_date_published_last_year and date_published >= add_months(max_date_published_last_year, -12) then 'YEAR_AGO_1_YEAR' else '' end) as MAT_MAPPING,\
(case when date_published >= date_published_start_of_year then 'YTD'\
when date_published <= max_date_published_last_year and date_published >= date_published_start_of_last_year\
then 'YTD_LAST_YEAR'\
else '' end) as YTD_MAPPING from\
(select t.country, t.date_published, t.date_published_ya, t.max_date_published_current_year,\
cast(add_months(t.max_date_published_current_year, -12) as timestamp) as max_date_published_last_year,\
date_trunc('year', max_date_published_current_year) AS date_published_start_of_year,\
date_trunc('year', cast(add_months(t.max_date_published_current_year, -12) as timestamp)) AS date_published_start_of_last_year\
from\
(select country,\
date_published,cast(add_months(date_published, -12) as timestamp) as date_published_ya,\
max(date_published)over(partition by country order by date_published desc) max_date_published_current_year from df_mintel_time) t) t2")
请添加您尝试过的代码。?我尝试过为每个国家创建一个包含max_date的数据框,然后对其进行相应的筛选,但数据集中存在多个国家,这使其变得复杂。@anidev711为什么要对其进行分组?您只需要将日期映射到不同的bucket,对吗?是的,而不是分组,说不同的分区是正确的。使用sql解决了这个问题。