Spark分类数据编码

时间:2015-04-07 19:45:58

标签: apache-spark apache-spark-mllib

Spark中是否有一个函数可以进行分类数据编码。 例如:

Var1,Var2,Var3
1,2,a
2,3,b
3,2,c

var1,var2,var3
1,2,0
2,3,1
3,2,2

a -> 0, b->1, c->2

2 个答案:

答案 0 :(得分:2)

将此功能用于分类数据编码。

def get_mapping(rdd, idx):
    return rdd.map(lambda x: x[idx]).distinct().zipWithIndex().collectAsMap()

的Scala

val categories = rdd.map(r => r(2)).distinct.collect.zipWithIndex.toMap

答案 1 :(得分:0)

Python - PySpark 2.0.0 +

df = pd.read_csv("file.csv",keep_default_na=False)
df = spark.createDataFrame(df)
types =  df1.dtypes
arity = {}
i=0
for c,t in types:
    if(t == 'string'):
        arity[i] = len(df1.select(c).distinct().collect())
        print arity[i],i,c
    i+=1

此arity字典可以作为 categoricalFeaturesInfo

的输入