1

在一列中有一個空值的數據框(並非全部爲空),它需要用uuid填充空值,有沒有辦法?如何將數據框中的空值填充到uuid?

cala> val df = Seq(("stuff2",null,null), ("stuff2",null,Array("value1","value2")),("stuff3","stuff3",null)).toDF("field","field2","values") 
     df: org.apache.spark.sql.DataFrame = [field: string, field2: string, values: array<string>] 

     scala> df.show 
     +------+------+----------------+ 
     | field|field2|   values| 
     +------+------+----------------+ 
     |stuff2| null|   null| 
     |stuff2| null|[value1, value2]| 
     |stuff3|stuff3|   null| 
     +------+------+----------------+ 

我試過這種方式,但「field2」的每一行都有相同的uuid。

scala> val fillDF = df.na.fill(java.util.UUID.randomUUID().toString(), Seq("field2")) 
    fillDF: org.apache.spark.sql.DataFrame = [field: string, field2: string, values: array<string>] 

scala> fillDF.show 
+------+--------------------+----------------+ 
| field|    field2|   values| 
+------+--------------------+----------------+ 
|stuff2|d007ffae-9134-4ac...|   null| 
|stuff2|d007ffae-9134-4ac...|[value1, value2]| 
|stuff3|    stuff3|   null| 
+------+--------------------+----------------+ 

如何製作它?萬一有100多萬行

回答

2

您可以使用UDF和​​3210來做到這一點,如下所示。

import org.apache.spark.sql.functions.udf 
val arr = udf(() => java.util.UUID.randomUUID().toString()) 

val df2 = df.withColumn("field2", coalesce(df("field2"), arr())) 
df2.show() 

您將得到與下面不同的UUID。

+------+--------------------+----------------+ 
| field|    field2|   values| 
+------+--------------------+----------------+ 
|stuff2|fda6bc42-1265-407...|   null| 
|stuff2|3fa74767-abd7-405...|[value1, value2]| 
|stuff3|    stuff3|   null| 
+------+--------------------+----------------+ 
+0

謝謝阿蓋爾,這個作品,我會接受它作爲答案。 –

0

您可以輕鬆地通過使用UDF做到這一點,它可以是這樣的:

def generateUUID(value: String):String = { 
    import java.util.UUID 
    if (Option(value).isDefined) { 
     value 
    } 
    else { 
     UUID.randomUUID().toString 
    } 
    val funcUDF = generateUUID _ 
    val generateUUID = udf(funcUDF) 

現在通過fillDF accrodingly:

fillDF.withColumns("field2",generateUUID(fillDF("field2"))).show 

PS:代碼沒有經過測試,但它應該工作!