dataframe - PySpark:如何使用`StringIndexer`对字符串数组列进行标签编码
问题描述
众所周知,我们可以在字符串列上做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]|
解决方案
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))
推荐阅读
- spring - Spring Boot 页面刷新有一些 404 请求
- android - 在 BottomNavigationView 中禁用 tooltipText
- ruby-on-rails - 使用 ActiveRecord 在哪里找不到记录时如何失败?
- android - 无法在 Google Play 管理中心开启定时发布模式
- sql - Oracle 内联视图列别名仅在加入表之前有效,而在加入表时无效
- php - 回调函数中php打开和关闭标签的奇怪用法
- python-3.x - 无法导入模块“lambda_function”:没有名为“pandas”的模块
- arrays - 复制时避免 bash 拆分字符串数组
- angular - 由 array.push() 制作的数组有元素但不能使用 angular
- mysql - MySQL 如果存在则选择列,否则选择另一列