PySpark When
PySpark When
PySpark When
- PySpark DataFrame에서 조건에 따라 다른 값을 내고 싶은 경우 사용하는 메서드. If-Else를 생각하면 된다
when(condition, "a").otherwise("b")
와 같이 사용- 조건을 만족하지 않는데
otherwise
가 없는 경우, None을 반환
- 조건을 만족하지 않는데
- 다음은 사용 예제
from pyspark.sql.functions import when
# 아래와 같이 chaining도 가능
df = df.withColumn("class", when(df.score > 90, "S")
.when(df.score > 75, "A")
.when(df.score > 60, "B")
.otherwise("C"))
References
- https://spark.apache.org/docs/3.1.2/api/python/reference/api/pyspark.sql.functions.when.html
- https://sparkbyexamples.com/pyspark/pyspark-when-otherwise/