【问题标题】:Pyspark: how to fix 'could not parse datatype: interval' errorPyspark:如何修复“无法解析数据类型:间隔”错误
【发布时间】:2022-01-17 21:11:15
【问题描述】:

我正在尝试通过减去两个现有列的值来向 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 date_of_birth current_date
01 1995-01-01 2021-12-2021
02 1987-02-16 2021-12-2021

我通过减去date_of_birthcurrent_date 的值插入了age 列。

df = df.withColumn('age', (df['current_date'] - df['date_of_birth ']))

单元运行没有问题。

这就是我卡住的地方:

一旦我尝试再次显示我的数据框以验证一切顺利,就会出现以下错误:

'无法解析数据类型:区间'

我使用 df.types() 检查发生了什么,显然我新插入的 age 列属于区间类型。

我该如何解决这个问题?

在这种特殊情况下,有没有办法以岁数 (int) 显示年龄?

PS:date_of_birthcurrent_date 列都有 date 类型。

【问题讨论】:

    标签: dataframe date pyspark


    【解决方案1】:

    将使用 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

    【讨论】:

    • 完美,工作,谢谢:)
    【解决方案2】:

    解决了。迈克的评论帮助了很多人。谢谢!

    我是这样解决的:

    
    # 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'))
    

    【讨论】:

      猜你喜欢
      • 2018-11-18
      • 2022-01-15
      • 2020-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 2019-10-12
      • 1970-01-01
      相关资源
      最近更新 更多