본문 바로가기

Data&Processing

Spark Dataframe에서 특정 컬럼이 없을경우 한 문장으로 컬럼 추가하기

How to add Spark Dataframe Column, when the column does not exist.

spark dataframe 생성 후에 table로 변환 후 쿼리를 적용한다거나 할때 항상 들어오던 column 이 없을경우 오류가 발생할수 있습니다.

하나씩 추가하는것보다는 Column Sets와 fold를 사용해서 한꺼번에 처리하는 방법 소개합니다.

dataframe이 df일경우, 누락될수 있는 컬럼List를 Set로 만들고 다음과 같이 적용합니다.

 

(Set("column1","column2", "column3") -- df.columns.toSet).foldLeft(df)((df, col) => df.withColumn(col , lit("") ) ).createOrReplaceTempView("tmp")