2016-11-17 2 views
0

Ich möchte Nan Werte in Spark Conditionally füllen (um sicherzustellen, dass ich jeden Eckfall meiner Daten berücksichtigt und nicht einfach nur etwas mit einem Ersatzwert füllen).funken bedingter Ersatz, aber behalten Sie archivierte Werte

konnte Eine Probe aussehen

case class FooBar(foo:String, bar:String) 
val myDf = Seq(("a","first"),("b","second"),("c",null), ("third","fooBar"), ("someMore","null")) 
     .toDF("foo","bar") 
     .as[FooBar] 

+--------+------+ 
|  foo| bar| 
+--------+------+ 
|  a| first| 
|  b|second| 
|  c| null| 
| third|fooBar| 
|someMore| null| 
+--------+------+ 

Leider alle
myDf 
     .withColumn(
      "bar", 
      when(
      (($"foo" === "c") and ($"bar" isNull)) , "someReplacement" 
     ) 
     ).show 

setzt regelmäßig andere Werte in der Spalte

+--------+---------------+ 
|  foo|   bar| 
+--------+---------------+ 
|  a|   null| 
|  b|   null| 
|  c|someReplacement| 
| third|   null| 
|someMore|   null| 
+--------+---------------+ 

und

myDf 
    .withColumn(
     "bar", 
     when(
     (($"foo" === "c") and ($"bar" isNull)) or 
     (($"foo" === "someMore") and ($"bar" isNull)), "someReplacement" 
    ) 
    ).show 

Welche ich wirklich verwenden möchte, um die Werte für verschiedene Klassen/Kategorien von foo auszufüllen. funktioniert nicht so gut.

Ich bin neugierig, wie das zu beheben ist.

Antwort

5

Verwendung otherwise:

when(
    (($"foo" === "c") and ($"bar" isNull)) or 
    (($"foo" === "someMore") and ($"bar" isNull)), "someReplacement" 
).otherwise($"bar") 

oder coalesce:

coalesce(
    $"bar", 
    when(($"foo" === "c") or ($"foo" === "someMore"), "someReplacement") 
) 

Der Grund für coalesce ist ... weniger tippen (so dass Sie nicht $"bar" isNull wiederholen).

Verwandte Themen