将标签字符串转换为二进制向量 pyspark
Convert strings of tags to binary vector pyspark
我有这样的数据:
| Id | ----Tags---- | some_text |
| 0 | <a><b> | ex1 |
| 1 | <a><c> | ex2 |
| 2 | <b><c> | ex3 |
我希望它最终看起来像这样:
| Id | a | b | c | some_text |
| 0 | 1 | 1 | 0 | ex1 |
| 1 | 1 | 0 | 1 | ex2 |
| 2 | 0 | 1 | 1 | ex3 |
并且我想使用 pyspark 作为解决方案。关于如何解决这个问题有什么想法吗?
如果您还不知道预期的分类值,可以使用 pyspark.sql.functions.udf
拆分和标记为值数组,并使用 pyspark.sql.functions.explode
函数将它们转换为列。然后,您可以将值转换为列:
# required imports
import pyspark.sql.functions as F
from pyspark.sql.types import ArrayType, StringType
import re
# regex pattern to split 'tagged values'
pat = re.compile('<(.*?)>')
#udf to split string to array of values
split_f = f.udf(lambda s: pat.split(s), ArrayType(StringType()))
# sample data
df = spark.createDataFrame([(0,'<a><b>','ex1'),(1,'<a><c>','ex2')], ['Id', '---Tags---', 'some_text'])
+---+----------+---------+
| Id|---Tags---|some_text|
+---+----------+---------+
| 0| <a><b>| ex1|
| 1| <a><c>| ex2|
+---+----------+---------+
df.withColumn('exploded',
F.explode(split_f(F.col('---Tags---'))))
.groupby('Id').pivot('exploded').count().na.fill(0).show()
+---+---+---+---+
| Id| a| b| c|
+---+---+---+---+
| 0| 1| 1| 0|
| 1| 1| 0| 1|
+---+---+---+---+
我有这样的数据:
| Id | ----Tags---- | some_text |
| 0 | <a><b> | ex1 |
| 1 | <a><c> | ex2 |
| 2 | <b><c> | ex3 |
我希望它最终看起来像这样:
| Id | a | b | c | some_text |
| 0 | 1 | 1 | 0 | ex1 |
| 1 | 1 | 0 | 1 | ex2 |
| 2 | 0 | 1 | 1 | ex3 |
并且我想使用 pyspark 作为解决方案。关于如何解决这个问题有什么想法吗?
如果您还不知道预期的分类值,可以使用 pyspark.sql.functions.udf
拆分和标记为值数组,并使用 pyspark.sql.functions.explode
函数将它们转换为列。然后,您可以将值转换为列:
# required imports
import pyspark.sql.functions as F
from pyspark.sql.types import ArrayType, StringType
import re
# regex pattern to split 'tagged values'
pat = re.compile('<(.*?)>')
#udf to split string to array of values
split_f = f.udf(lambda s: pat.split(s), ArrayType(StringType()))
# sample data
df = spark.createDataFrame([(0,'<a><b>','ex1'),(1,'<a><c>','ex2')], ['Id', '---Tags---', 'some_text'])
+---+----------+---------+
| Id|---Tags---|some_text|
+---+----------+---------+
| 0| <a><b>| ex1|
| 1| <a><c>| ex2|
+---+----------+---------+
df.withColumn('exploded',
F.explode(split_f(F.col('---Tags---'))))
.groupby('Id').pivot('exploded').count().na.fill(0).show()
+---+---+---+---+
| Id| a| b| c|
+---+---+---+---+
| 0| 1| 1| 0|
| 1| 1| 0| 1|
+---+---+---+---+