![](/img/trans.png)
[英]About how to add a new column to an existing DataFrame with random values in Scala
[英]How to add a new nullable String column in a DataFrame using Scala
可能至少有10个问题与此非常相似,但我仍然没有找到明确的答案。
如何使用 scala 将可为空的字符串列添加到 DataFrame? 我能够添加具有 null 值的列,但 DataType 显示 null
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 中。
只需将 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)
为什么你想要一个总是 null 的列? 有几种方法,我更喜欢typedLit
的解决方案:
myDF.withColumn("newcolumn", typedLit[String](null))
或者对于旧的 Spark 版本:
myDF.withColumn("newcolumn",lit(null).cast(StringType))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.