【问题标题】:How to add a new nullable String column in a DataFrame using Scala如何使用 Scala 在 DataFrame 中添加新的可为空字符串列
【发布时间】:2019-10-17 22:28:13
【问题描述】:

可能至少有10个问题与此非常相似,但我仍然没有找到明确的答案。

如何使用 scala 将可为空的字符串列添加到 DataFrame?我能够添加具有空值的列,但 DataType 显示为空

val testDF = myDF.withColumn("newcolumn", when(col("UID") =!= "not", null).otherwise(null))

但是,架构显示

root
 |-- UID: string (nullable = true)
 |-- IsPartnerInd: string (nullable = true)
 |-- newcolumn: null (nullable = true)

我希望新列是字符串 |-- newcolumn: string (nullable = true)

请不要标记为重复,除非它确实是同一个问题并且在 scala 中。

【问题讨论】:

  • 试试myDF.withColumn("newcolumn", lit(null).cast("string"))

标签: scala apache-spark


【解决方案1】:

只需将 null 文字显式转换为 StringType

scala> val testDF = myDF.withColumn("newcolumn", when(col("UID") =!= "not", lit(null).cast(StringType)).otherwise(lit(null).cast(StringType)))

scala> testDF.printSchema

root
 |-- UID: string (nullable = true)
 |-- newcolumn: string (nullable = true)

【讨论】:

    【解决方案2】:

    为什么你想要一个总是为空的列?有几种方法,我更喜欢typedLit的解决方案:

    myDF.withColumn("newcolumn", typedLit[String](null))
    

    或者对于旧的 Spark 版本:

    myDF.withColumn("newcolumn",lit(null).cast(StringType))
    

    【讨论】:

      猜你喜欢
      • 2023-02-02
      • 2011-09-27
      • 2015-06-27
      • 1970-01-01
      • 2018-11-04
      • 2018-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多