簡體   English   中英

Spark Scala計算數據框字段的長度

[英]Spark Scala to count length in dataframe fields

Scala新手。

我在scala中創建了一個子串函數,它需要“pos”和“len”,我希望pos是硬編碼的,但是對於它應該從數據幀中計算它的長度。 我該怎么做呢?

這是我的代碼:

val A = DF.select(col("example_ref"), substring(col("example_ref"),11, 21))

提前致謝。

編輯:

所以添加了這段代碼:

val A = DF.select($"example_ref",substring($"example_ref",11,length($"example_ref")))

但是我收到以下錯誤:

Type Mismatch, expected: String, actual: Column
Type Mismatch, expected: Int, actual: Column

您可以創建UDF以獲取列的長度,然后將子字符串函數封裝在expr函數中

val colLength = udf { (col: String) => col.size }

然后在您的代碼中使用它

val A = DF.select(col("example_ref"), expr("substring(col(example_ref),11, colLength(col(example_ref)))"))

PS。 我最喜歡使用美元語法來獲取列

val A = DF.select($"example_ref", expr("substring(example_ref,11, colLength(example_ref))"))

編輯

正如評論中指出的那樣,已經有了一個功能,所以你甚至不需要定義UDF:

import org.apache.spark.sql.functions.length
val A = DF.select($"example_ref", expr("substring(example_ref,11, length(example_ref))"))

快速示例

INPUT

scala> val df = sc.parallelize(List((1, "abc"),(2, "bcd"),(3, "cde"))).toDF("number", "mycolumn")
df: org.apache.spark.sql.DataFrame = [number: int, mycolumn: string]

scala> df.show
+------+--------+
|number|mycolumn|
+------+--------+
|     1|     abc|
|     2|     bcd|
|     3|     cde|
+------+--------+

OUTPUT

df.select(expr("substring(mycolumn, 2, length(mycolumn))")).show
+----------------------------------------+
|substring(mycolumn, 2, length(mycolumn))|
+----------------------------------------+
|                                      bc|
|                                      cd|
|                                      de|
+----------------------------------------+

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM