2016-03-08 119 views
6

pyspark矩阵有两列:与虚拟变量

ID Text 
1 a 
2 b 
3 c 

我如何能够创建虚拟变量这样的矩阵:

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

使用pyspark库及其特点?

回答

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() 

输出

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

回溯(最近通话最后一个): 文件 “”,2号线,在 NameError:名字 'F' 没有定义 –

+1

什么是F在这里?从pyspark.sql的 –

+1

导入函数为F –