我想修改 spark df 中的日期列,以僅在出現某些月份時減去 1 個月。即僅當日期為 yyyy-07-31 或日期為 yyyy-04-30 時,將其分別更改為 yyyy-06-31 和 yyyy-03-30。任何想法如何使用 pyspark 函式來做到這一點?
|DateColumn|
|2016-04-30|
|2015-04-30|
|2017-09-03|
|2017-07-31|
|2016-09-01|
|2018-07-31|
...
預期結果:
|DateColumn|
|2016-03-30| <- changed
|2015-03-30| <- changed
|2017-09-03|
|2017-06-31| <- changed
|2016-09-01|
|2018-06-31| <- changed
...
uj5u.com熱心網友回復:
我建議使用該functions模塊,然后結合幾個功能:
.when()進而otherwise().month().date_format().add_months(date, -1)
例如,它可以歸結為:
import pyspark.sql.functions as F
df = spark.createDataFrame([{'date': '2022-04-15'}, {'date': '2022-05-17'}])
df \
.withColumn('new_date',
F.when(F.month(F.col('date')).isin([4, 7]),
F.add_months(F.date_format('date', 'yyyy-MM-dd'), -1))
.otherwise(F.col('date'))) \
.show()
然后你會得到:
---------- ----------
| date| new_date|
---------- ----------
|2022-04-15|2022-03-15|
|2022-05-17|2022-05-17|
---------- ----------
更新 (原來它是子字串問題而不是通用月份減去,請參閱評論了解詳細資訊)
實際上,您可以堆疊功能以在 Python.when中執行某種操作。if-elif-else下面的代碼顯示了如何在您共享的場景中執行它:
from pyspark.sql.functions import when
df \
.withColumn('new_date',
when(F.substring(F.col("date"), -5, 5) == '01-31', F.concat(F.year(F.col("date")), F.lit('-12-31')))
.when(F.substring(F.col("date"), -5, 5) == '04-30', F.concat(F.year(F.col("date")), F.lit('-03-30')))
.when(F.substring(F.col("date"), -5, 5) == '07-31', F.concat(F.year(F.col("date")), F.lit('-06-30')))
.when(F.substring(F.col("date"), -5, 5) == '10-31', F.concat(F.year(F.col("date")), F.lit('-09-30')))
.otherwise(F.col('date'))) \
.show()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/474819.html
