【问题标题】:Dataframe withColumn and null数据框 withColumn 和 null
【发布时间】:2018-12-23 05:47:26
【问题描述】:

我有一个使用DataFrame.withColumn的简单代码

  test("SparkSQLTest") {
    val spark = SparkSession.builder().master("local").appName("SparkSQLTest").getOrCreate()
    import spark.implicits._
    var df = spark.createDataset(
      Seq(
        ("1", "2"),
        ("3", "4")
      )
    ).toDF("a", "b")
    df = df.withColumn("c", functions.lit(null.asInstanceOf[String]).as[String])
    df.printSchema()
    df.show(truncate = false)
  }

输出架构是:

root
 |-- a: string (nullable = true, metadata = {})
 |-- b: string (nullable = true, metadata = {})
 |-- c: null (nullable = true, metadata = {})

c 列的类型为空,我以为是字符串。如果为 null,则无法写入 csv,因为不支持 null 数据类型。

我会问如何使 c 的类型正确。

【问题讨论】:

标签: apache-spark


【解决方案1】:

我试过了,效果很好。

df = df.withColumn("c", functions.lit(null.asInstanceOf[String]).cast(StringType))

对不起,应该是演员...我已经修改了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-21
    • 1970-01-01
    • 2018-09-18
    相关资源
    最近更新 更多