将半结构化字符串转换为 pyspark 数据帧
Convert semi-structured string to pyspark dataframe
我得到了以下数据框
+---+--------------------------------------+
| id| score|
+---+--------------------------------------+
| 1|(math, 90)(physics, 87)(chemistry, 82)|
+---+--------------------------------------+
| 2| (computer, 84)|
+---+--------------------------------------+
| 3| null|
+---+--------------------------------------+
其中 score
列的类型为 str
。
我想将此 str
转换为 array<str>
如下所示
+---+--------------------------------------------+
| id| score|
+---+--------------------------------------------+
| 1|['math, 90', 'physics, 87', 'chemistry, 82']|
+---+--------------------------------------------+
| 2| ['computer, 84']|
+---+--------------------------------------------+
| 3| null|
+---+--------------------------------------------+
所以基本上它将字符串拆分为一个数组并删除所有括号。
我正在引用 问题,但我不太确定要使用的正确正则表达式是什么。
感谢并感谢您的帮助。
这应该仅使用 Spark SQL 函数即可为您提供所需的输出。
纯粹用 Spark SQL 函数来做有点复杂。 UDF 可能会提供更清晰的结果,但不确定对性能的影响。
from pyspark.sql import functions as F
testDF = spark.createDataFrame([
(1, "(math, 90)(physics, 87)(chemistry, 82)"),
(2, "(computer, 84)"),
(3, "null")
], ["id", "score"])
testDF.select('id', F.split('score', '[)][(]').alias('score'))\
.select('id', F.explode('score').alias('score'))\
.select('id', F.regexp_replace('score', '[)]|[(]', '').alias('score'))\
.groupBy('id')\
.agg(F.collect_list("score").alias("score"))\
.orderBy('id')\
.show()
请注意 array/list 元素周围的引号不会出现。但是如果你 运行 collect()
而不是 show()
.
你可以看到它
我得到了以下数据框
+---+--------------------------------------+
| id| score|
+---+--------------------------------------+
| 1|(math, 90)(physics, 87)(chemistry, 82)|
+---+--------------------------------------+
| 2| (computer, 84)|
+---+--------------------------------------+
| 3| null|
+---+--------------------------------------+
其中 score
列的类型为 str
。
我想将此 str
转换为 array<str>
如下所示
+---+--------------------------------------------+
| id| score|
+---+--------------------------------------------+
| 1|['math, 90', 'physics, 87', 'chemistry, 82']|
+---+--------------------------------------------+
| 2| ['computer, 84']|
+---+--------------------------------------------+
| 3| null|
+---+--------------------------------------------+
所以基本上它将字符串拆分为一个数组并删除所有括号。
我正在引用
感谢并感谢您的帮助。
这应该仅使用 Spark SQL 函数即可为您提供所需的输出。
纯粹用 Spark SQL 函数来做有点复杂。 UDF 可能会提供更清晰的结果,但不确定对性能的影响。
from pyspark.sql import functions as F
testDF = spark.createDataFrame([
(1, "(math, 90)(physics, 87)(chemistry, 82)"),
(2, "(computer, 84)"),
(3, "null")
], ["id", "score"])
testDF.select('id', F.split('score', '[)][(]').alias('score'))\
.select('id', F.explode('score').alias('score'))\
.select('id', F.regexp_replace('score', '[)]|[(]', '').alias('score'))\
.groupBy('id')\
.agg(F.collect_list("score").alias("score"))\
.orderBy('id')\
.show()
请注意 array/list 元素周围的引号不会出现。但是如果你 运行 collect()
而不是 show()
.