1. 程式人生 > >spark 常見操作

spark 常見操作

為spark DataFrom 新增一個為 空的新列,使用UDF函式

想產生一個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")
  // 利用 取不存在的值 會返回 Node 實現 返回空
val udf_null = udf((s: Any) => Map("k"->"v").get("l"))
// 新增 新列 col3, 使用col1 列作為引數傳入, 對 udf_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|
+----+