我们知道,scala中Int类型不能为null
,
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.printSchemaroot |-- 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|+----+----+----+