首页 > 解决方案 > 在火花数据框中将字符串拆分为两列

问题描述

我有一个数据框,其行值“我的名字是 Rahul”我想将“我的名字是”拆分为一列,将“Rahul”拆分为另一列。这里没有使用 split 函数的分隔符。我怎样才能在火花中做到这一点?

标签: scalaapache-sparksplit

解决方案


在 Spark 中Split使用函数而不是函数。regexp_extract

Regex Explanation:

(.*)\\s(.*) //capture everything into 1 capture group until last space(\s) then capture everything after into 2 capture group.

Example:

val df= Seq(("My name is Rahul")).toDF("text") //sample string

df.withColumn("col1",regexp_extract($"text","(.*)\\s(.*)",1)).
withColumn("col2",regexp_extract($"text","(.*)\\s(.*)",2)).
show()

Result:

+----------------+----------+-----+
|            text|      col1| col2|
+----------------+----------+-----+
|My name is Rahul|My name is|Rahul|
+----------------+----------+-----+

推荐阅读