spark scala dataframe을 withColumn
을 통해 한줄한줄 iteration을 돌려 처리가 가능하다.
내가 원하는 함수에 한개의 row를 넘기고, 그 처리된 결과를 새로운 column으로 생성한다.
예제코드
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.apache.spark.sql.functions._ | |
import org.apache.spark.sql.expressions.UserDefinedFunction | |
val sampleFunc: (Double, Double, Int) => Double = { | |
(value1: Double, value2: Double, cnt: Int) => | |
value1 + value2 + cnt | |
} | |
val sampleUdf: UserDefinedFunction = udf(sampleFunc) | |
val df2 = df.withColumn("newColumn", sampleUdf($"col1", $"col2", lit(1))) | |
df2.show() |
sampleFunc
을 생성하고UserDefinedFunction
,udf
를 통해sampleUdf
를 생성- 생성된
sampleUdf
는DataFrame
의withColumn
을 이용- 첫번째 파라미터는
withColumn
을 통해 생성될 신규 컬럼명 - 두번째 파라미터는
udfFunction
+ parameters - 여기서
lit
은 constant 값을 넘길때 사용한다.
- 첫번째 파라미터는
'우리는 개발자 > Data Engineering' 카테고리의 다른 글
[Spark] SchemaField nullable state 변경하는 방법 (0) | 2020.02.28 |
---|---|
[Spark] scala DataFrame 생성하기 for 예제 (0) | 2020.02.27 |
[Spark] Scala joda Datetime 사용하는 방법 (+예제코드) - Days, DateTimeFormat, DateTime (0) | 2020.02.27 |
[Spark] 시작할때 살펴보면 좋은 유용한 사이트 모음 (0) | 2020.02.27 |
[Spark] Scala Test (Library, Sbt Test) (0) | 2020.02.26 |