首页 > 解决方案 > PySpark 2.2中数组列的每个元素的子串

问题描述

我想在 PySpark 2.2 中对数组列的每个元素进行子串化。我的 df 看起来像下面的那个,类似于this,尽管我的 df 中的每个元素在连字符分隔符之前的长度相同。

+---------------------------------+----------------------+
|col1                             |new_column            |
+---------------------------------+----------------------+
|[hello-123, abcde-111]           |[hello, abcde]        |
|[hello-234, abcde-221, xyzhi-333]|[hello, abcde, xyzhi] |
|[hiiii-111, abbbb-333, xyzhu-222]|[hiiii, abbbb, xyzhu] |
+---------------------------------+----------------------+

我尝试根据答案调整上一个问题中的 udf 以获得new_column上面的输出,但到目前为止还没有运气。有没有办法在 PySpark 2.2 中完成这项工作?

import pyspark.sql.functions as F
import pyspark.sql.types as T 

cust_udf = F.udf(lambda arr: [x[0:4] for x in arr], T.ArrayType(T.StringType()))
df1.withColumn('new_column', cust_udf(col("col1")))

标签: pythonarrayspysparkapache-spark-sql

解决方案


你的 udf 方法对我有用。此外,您可以使用transformwith substring

import pyspark.sql.functions as f

df.withColumn('new_column', f.expr('transform(col1, x -> substring(x, 0, 5))')).show()

+--------------------+--------------------+
|                col1|          new_column|
+--------------------+--------------------+
|[hello-123, abcde...|      [hello, abcde]|
|[hello-234, abcde...|[hello, abcde, xy...|
|[hiiii-111, abbbb...|[hiiii, abbbb, xy...|
+--------------------+--------------------+

推荐阅读