假設您有一個資料框 df ,如下所示:
ID Years Date
A 5 2021-02-01
B 3 2021-02-01
C 6 2021-02-01
我希望能夠創建一個額外的日期陣列列,其中所有日期從初始日期 1 個月一直到年列中的 x 年。它如下所示:
ID Years Date Dates
A 5 2021-02-01 [2021-03-01,2021-04-01,...,2026-02-01]
B 3 2021-03-01 [2021-04-01,2021-04-01,...,2024-03-01]
C 6 2021-02-01 [2021-03-01,2021-04-01,...,2027-02-01]
uj5u.com熱心網友回復:
對于 spark >= 2.4,您可以使用sequence和add_months函式來生成所需的日期序列。
df = df.withColumn('Dates',
F.expr('sequence(add_months(to_date(Date), 1), add_months(to_date(Date), int(Years) * 12), interval 1 month)')
)
df.show(truncate=False)
uj5u.com熱心網友回復:
我不是 PySpark 方面的專家,而且我聽說在某些情況下將 PySpark 更改為 pandas 資料框并不有趣。但如果沒問題,您可以將格式更改為 pandas 并嘗試使用apply函式:
df = df_spark.toPandas()
def getRangeDate(row):
return list(map(lambda x: x.strftime("%Y-%m-%d"), list(pd.date_range(start = row["Date"], periods = 12*row["Years"] 1, freq = 'MS'))[1:]))
df['Dates'] = df.apply(getRangeDate, axis=1)
df
其中,關于您的示例輸入,具有以下輸出:
ID Years Date Dates
0 A 5 2021-02-01 [2021-03-01, 2021-04-01, 2021-05-01, ..., 2026-02-01]
1 B 3 2021-03-01 [2021-04-01, 2021-05-01, 2021-06-01, ..., 2024-03-01]
2 C 6 2021-02-01 [2021-03-01, 2021-04-01, 2021-05-01, ..., 2027-02-01]
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/431711.html
下一篇:比較2個資料框的部分相似性
