如何使用Scala在数据帧中添加新的可空字符串列
可能至少有10个问题与此非常相似,但我仍然没有找到明确的答案 如何使用scala将可为空的字符串列添加到数据帧?我可以添加一个具有null值的列,但是数据类型显示null如何使用Scala在数据帧中添加新的可空字符串列,scala,apache-spark,Scala,Apache Spark,可能至少有10个问题与此非常相似,但我仍然没有找到明确的答案 如何使用scala将可为空的字符串列添加到数据帧?我可以添加一个具有null值的列,但是数据类型显示null val testDF = myDF.withColumn("newcolumn", when(col("UID") =!= "not", null).otherwise(null)) 然而,模式显示 root |-- UID: string (nullable = true) |-- IsPartnerInd: stri
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)
我希望新列为string|--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文本强制转换为
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)
为什么希望列始终为空?有几种方法,我更喜欢使用
typedLit
的解决方案:
myDF.withColumn("newcolumn", typedLit[String](null))
或对于较旧的Spark版本:
myDF.withColumn("newcolumn",lit(null).cast(StringType))
为什么希望列始终为空?有几种方法,我更喜欢使用
typedLit
的解决方案:
myDF.withColumn("newcolumn", typedLit[String](null))
或对于较旧的Spark版本:
myDF.withColumn("newcolumn",lit(null).cast(StringType))
尝试myDF.withColumn(“newcolumn”,lit(null).cast(“string”)
。尝试myDF.withColumn(“newcolumn”,lit(null).cast(“string”)
。