![enter image description here](https://i.stack.imgur.com/qptVG.png)
我希望使用 Pyspark 语法将分类变量虚拟编码为数值变量,如下图所示。
我读入这样的数据
data = sqlContext.read.csv("data.txt", sep = ";", header = "true")
在 python 中,我可以使用下面的代码对变量进行编码
data = pd.get_dummies(data, columns = ['Continent'])
但是我不知道如何在 Pyspark 中做到这一点。
任何帮助将不胜感激。
尝试这个:
import pyspark.sql.functions as F
categ = df.select('Continent').distinct().rdd.flatMap(lambda x:x).collect()
exprs = [F.when(F.col('Continent') == cat,1).otherwise(0)\
.alias(str(cat)) for cat in categ]
df = df.select(exprs+df.columns)
如果您不希望转换后的数据框中包含原始列,请排除 df.columns。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)