2
我正在使用Spark 2.0和Python API。在Spark中獲取上個星期一
我有一個類型爲DateType()的列的數據框。我想向包含最近星期一的數據框添加一列。
我能做到這一點是這樣的:
reg_schema = pyspark.sql.types.StructType([
pyspark.sql.types.StructField('AccountCreationDate', pyspark.sql.types.DateType(), True),
pyspark.sql.types.StructField('UserId', pyspark.sql.types.LongType(), True)
])
reg = spark.read.schema(reg_schema).option('header', True).csv(path_to_file)
reg = reg.withColumn('monday',
pyspark.sql.functions.when(pyspark.sql.functions.date_format(reg.AccountCreationDate,'E') == 'Mon',
reg.AccountCreationDate).otherwise(
pyspark.sql.functions.when(pyspark.sql.functions.date_format(reg.AccountCreationDate,'E') == 'Tue',
pyspark.sql.functions.date_sub(reg.AccountCreationDate, 1)).otherwise(
pyspark.sql.functions.when(pyspark.sql.functions.date_format(reg.AccountCreationDate, 'E') == 'Wed',
pyspark.sql.functions.date_sub(reg.AccountCreationDate, 2)).otherwise(
pyspark.sql.functions.when(pyspark.sql.functions.date_format(reg.AccountCreationDate, 'E') == 'Thu',
pyspark.sql.functions.date_sub(reg.AccountCreationDate, 3)).otherwise(
pyspark.sql.functions.when(pyspark.sql.functions.date_format(reg.AccountCreationDate, 'E') == 'Fri',
pyspark.sql.functions.date_sub(reg.AccountCreationDate, 4)).otherwise(
pyspark.sql.functions.when(pyspark.sql.functions.date_format(reg.AccountCreationDate, 'E') == 'Sat',
pyspark.sql.functions.date_sub(reg.AccountCreationDate, 5)).otherwise(
pyspark.sql.functions.when(pyspark.sql.functions.date_format(reg.AccountCreationDate, 'E') == 'Sun',
pyspark.sql.functions.date_sub(reg.AccountCreationDate, 6))
)))))))
然而,這似乎是一個大量的代碼的東西,應該是相當簡單的。有沒有更簡潔的方式來做到這一點?