시간 특성

PySpark로 하는 Feature Engineering

John Hogue

Lead Data Scientist, General Mills

사물의 순환적 특성

시간 이미지

PySpark로 하는 Feature Engineering

적절한 수준 선택

일별 매출

PySpark로 하는 Feature Engineering

적절한 수준 선택

월별 매출

PySpark로 하는 Feature Engineering

날짜 필드를 날짜로 처리하기

from pyspark.sql.functions import to_date

# Cast the data type to Date
df = df.withColumn('LISTDATE', to_date('LISTDATE'))
# Inspect the field
df[['LISTDATE']].show(2)
+----------+
|  LISTDATE|
+----------+
|2017-07-14|
|2017-10-08|
+----------+
only showing top 2 rows
PySpark로 하는 Feature Engineering

시간 구성 요소

from pyspark.sql.functions import year, month

# Create a new column of year number
df = df.withColumn('LIST_YEAR', year('LISTDATE'))
# Create a new column of month number
df = df.withColumn('LIST_MONTH', month('LISTDATE'))
from pyspark.sql.functions import dayofmonth, weekofyear

# Create new columns of the day number within the month
df = df.withColumn('LIST_DAYOFMONTH', dayofmonth('LISTDATE'))
# Create new columns of the week number within the year
df = df.withColumn('LIST_WEEKOFYEAR', weekofyear('LISTDATE'))
PySpark로 하는 Feature Engineering

기본 시간 기반 지표

Days on Market 이미지

from pyspark.sql.functions import datediff

# Calculate difference between two date fields
df.withColumn('DAYSONMARKET', datediff('OFFMARKETDATE', 'LISTDATE'))
PySpark로 하는 Feature Engineering

래그 특성

컵에 떨어지는 커피 한 방울

window()

레코드 그룹을 기반으로 레코드를 반환합니다

lag(col, count=1)

현재 행 이전의 지정된 행만큼 오프셋된 값을 반환합니다

PySpark로 하는 Feature Engineering

PySpark 방식의 래그 특성

from pyspark.sql.functions import lag
from pyspark.sql.window import Window

# Create Window w = Window().orderBy(m_df['DATE'])
# Create lagged column m_df = m_df.withColumn('MORTGAGE-1wk', lag('MORTGAGE', count=1).over(w))
# Inspect results m_df.show(3)
+----------+------------+----------------+
|      DATE|    MORTGAGE|    MORTGAGE-1wk|
+----------+------------+----------------+
|2013-10-10|        4.23|            null|
|2013-10-17|        4.28|            4.23|
|2013-10-24|        4.13|            4.28|
+----------+------------+----------------+
only showing top 3 rows
PySpark로 하는 Feature Engineering

이제 연습할 시간입니다!

PySpark로 하는 Feature Engineering

Preparing Video For Download...