use length function in substring in spark

风流意气都作罢 提交于 2019-12-30 06:22:12

问题


I am trying to use the length function inside a substring function in a DataFrame but it gives error

val substrDF = testDF.withColumn("newcol", substring($"col", 1, length($"col")-1))

below is the error

 error: type mismatch;
 found   : org.apache.spark.sql.Column
 required: Int

I am using 2.1.


回答1:


Function "expr" can be used:

val data = List("first", "second", "third")
val df = sparkContext.parallelize(data).toDF("value")
val result = df.withColumn("cutted", expr("substring(value, 1, length(value)-1)"))
result.show(false)

output:

+------+------+
|value |cutted|
+------+------+
|first |firs  |
|second|secon |
|third |thir  |
+------+------+



回答2:


You could also use $"COLUMN".substr

val substrDF = testDF.withColumn("newcol", $"col".substr(lit(1), length($"col")-1))

Output:

val testDF = sc.parallelize(List("first", "second", "third")).toDF("col")
val result = testDF.withColumn("newcol", $"col".substr(org.apache.spark.sql.functions.lit(1), length($"col")-1))
result.show(false)
+------+------+
|col   |newcol|
+------+------+
|first |firs  |
|second|secon |
|third |thir  |
+------+------+



回答3:


You get that error because you the signature of substring is

def substring(str: Column, pos: Int, len: Int): Column 

The len argument that you are passing is a Column, and should be an Int.

You may probably want to implement a simple UDF to solve that problem.

val strTail = udf((str: String) => str.substring(1))
testDF.withColumn("newCol", strTail($"col"))



回答4:


If all you want is to remove the last character of the string, you can do that without UDF as well. By using regexp_replace :

testDF.show
+---+----+
| id|name|
+---+----+
|  1|abcd|
|  2|qazx|
+---+----+

testDF.withColumn("newcol", regexp_replace($"name", ".$" , "") ).show
+---+----+------+
| id|name|newcol|
+---+----+------+
|  1|abcd|   abc|
|  2|qazx|   qaz|
+---+----+------+


来源:https://stackoverflow.com/questions/46353360/use-length-function-in-substring-in-spark

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!