use length function in substring in spark

Viewed 44596

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.

5 Answers

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  |
+------+------+

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"))

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|
+---+----+------+

You have to use the SUBSTR function to achieve this.

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

The first parameter is the position from which you want the data to be trimmed, the second parameter is the length of the trimmed field. (startPos: Int,len: Int)

Related