我們知道,scala中Int類型不能為null
,
而Dataset中表示的Int值的IntegerType類型列卻能為null
。
如果我們想產生一個IntegerType類型列為null的DataFrame該怎么做?
下面的代碼可以做到:
import org.apache.spark.sql.functions._
import org.apache.spark.sql.types._
val df_json = spark.createDataFrame(List(
(1.2, 1),
(3.1, 2)))
.toDF("col1", "col2")
val udf_null = udf((s: Any) => null)
val df_res = df_json.withColumn("col3", udf_null(col("col1")).cast(IntegerType))
df_res.show
scala> df_res.printSchema
root
|-- col1: double (nullable = false)
|-- col2: integer (nullable = false)
|-- col3: integer (nullable = true)
scala> df_res.show
+----+----+----+
|col1|col2|col3|
+----+----+----+
| 1.2| 1|null|
| 3.1| 2|null|
+----+----+----+