2016-03-08 7 views
6

hat zwei Spalten:pyspark Matrix mit Dummy-Variablen

ID Text 
1 a 
2 b 
3 c 

Wie kann ich in der Lage Matrix mit Dummy-Variablen wie folgt zu erstellen:

ID a b c 
1 1 0 0 
2 0 1 0 
3 0 0 1 

Mit pyspark Bibliothek und ihre Funktionen?

Antwort

5
from pyspark.sql import functions as F 

df = sqlContext.createDataFrame([ 
    (1, "a"), 
    (2, "b"), 
    (3, "c"), 
], ["ID", "Text"]) 

categories = df.select("Text").distinct().rdd.flatMap(lambda x: x).collect() 

exprs = [F.when(F.col("Text") == category, 1).otherwise(0).alias(category) 
     for category in categories] 

df.select("ID", *exprs).show() 

Ausgabe

+---+---+---+---+ 
| ID| a| b| c| 
+---+---+---+---+ 
| 1| 1| 0| 0| 
| 2| 0| 1| 0| 
| 3| 0| 0| 1| 
+---+---+---+---+ 
+0

Traceback (jüngste Aufforderung zuletzt): File "", Zeile 2, in Nameerror: name 'F' –

+1

nicht definiert Was ist hier F? –

+1

von pyspark.sql Importfunktionen wie F –