【问题标题】:PySpark: how to use `StringIndexer` to do label encoding with the string array columnPySpark:如何使用`StringIndexer`对字符串数组列进行标签编码
【发布时间】:2020-11-05 21:16:18
【问题描述】:

众所周知,LabelEncoder()StringIndexer可以在字符串列上做,但如果要在字符串数组列上做LabelEncoder(),实现起来并不容易。

# input
df.show()

+--------------------------------------+
|                                  tags|
+--------------------------------------+
|        [industry, display, Merchants]|
|    [smart, swallow, game, Experience]|
|             [social, picture, social]|
|        [default, game, us, adventure]|
| [financial management, loan, product]|
|       [system, profile, optimization]|

...
# After do LabelEncoder() on `tags` column 
...

+--------------------------------------+
|                                  tags|
+--------------------------------------+
|                             [0, 1, 2]|
|                          [3, 4, 4, 5]|
|                             [6, 7, 6]|
|                         [8, 4, 9, 10]|
|                          [11, 12, 13]|
|                          [14, 15, 16]|

【问题讨论】:

    标签: dataframe apache-spark pyspark apache-spark-sql


    【解决方案1】:

    Python 版本将非常相似:

    // add unique id to each row
    val df2 = df.withColumn("id", monotonically_increasing_id).select('id, explode('tags).as("tag"))
    
    val indexer = new StringIndexer()
      .setInputCol("tag")
      .setOutputCol("tagIndex")
    
    val indexed = indexer.fit(df2).transform(df2)
    
    // in the final step you should convert tags back to array of tags
    val dfFinal = indexed.groupBy('id).agg(collect_list('tagIndex))
    

    【讨论】:

      猜你喜欢
      • 2019-05-06
      • 1970-01-01
      • 2019-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多