python - 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")))
解决方案
你的 udf 方法对我有用。此外,您可以使用transform
with 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...|
+--------------------+--------------------+
推荐阅读
- flutter - Flutter 版本约束误区
- asp.net-core - 是否可以在 asp.net 身份服务器 4 中自定义 IdentityUserRole 表?
- python - 检索根 id 给出空字典
- java - 如何从另一个任务打开 SingleTask Activity
- r - Sublink not working in r webscraping - df comes up with blank cells
- javascript - Laravel + adminLTE3 jquery and other dependencies not found
- git - 有没有一种简单的方法可以通过所有以前的提交来搜索 git repo 的所有代码?
- amazon-web-services - 如何在没有授权人的情况下配置 AWS API Gateway?
- php - 如何在 .htaccess 中为我的 404 自定义页面添加规则
- python - 如何解决 MDNavigationRail 中侧面图标的工作