带有虚拟变量的pyspark矩阵 [英] pyspark matrix with dummy variables
本文介绍了带有虚拟变量的pyspark矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有两列:
ID Text
1 a
2 b
3 c
如何使用伪变量创建矩阵,如下所示:
How can I able to create matrix with dummy variables like this:
ID a b c
1 1 0 0
2 0 1 0
3 0 0 1
使用pyspark库及其功能吗?
Using pyspark library and its features?
推荐答案
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|
+---+---+---+---+
这篇关于带有虚拟变量的pyspark矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文