我試圖通過減去兩個現有列的值來向 pyspark df 添加一個新列。
我已經有一個date_of_birth可用的列,所以我插入了一個current_date包含以下代碼的列:
import datetime
currentdate = "14-12-2021"
day,month,year = currentdate.split('-')
today = datetime.date(int(year),int(month),int(day))
df= df.withColumn("current_date", lit(today))
顯示我的 df 確認它有效。看起來有點像這樣:
| ID | 出生日期 | 當前日期 |
|---|---|---|
| 01 | 1995-01-01 | 2021-12-2021 |
| 02 | 1987-02-16 | 2021-12-2021 |
我插入age通過減去的值列date_of_birth和current_date。
df = df.withColumn('age', (df['current_date'] - df['date_of_birth ']))
細胞運行沒有問題。
這是我被困的地方:
一旦我嘗試再次顯示我的資料框以驗證一切順利,就會出現以下錯誤:
'無法決議資料型別:間隔'
我使用 df.types() 來檢查發生了什么,顯然我新插入的age列是間隔型別。
我怎樣才能解決這個問題?
在這種特定情況下,有沒有辦法以年(int)為單位顯示年齡?
PS: thedate_of_birth和current_datecols 都有日期型別。
uj5u.com熱心網友回復:
解決了。邁克的評論幫助了很多。謝謝!
這是我解決它的方法:
# insert new column current_date with dummy data (in this case, 1s)
df = df.withColumn("current_date", lit(1))
# update data with current_date() function
df = df .withColumn("current_date", f.current_date())
# insert new column age with dummy data (in this case, 1s)
df = df .withColumn("age", lit(1))
# update data with months_between() function, divide by 12 to obtain years.
df = df .withColumn("age", f.months_between(df.current_date, df .date_of_birth)/12)
# round and cast as interger to get rid of decimals
df = df .withColumn("age", f.round(df["age"]).cast('integer'))
uj5u.com熱心網友回復:
將使用 pyspark 函式之一來計算日期之間的差異。
pyspark.sql.functions.datediff
https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.sql.functions.datediff.html
pyspark.sql.functions.months_between
https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.sql.functions.months_between.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/384984.html
