[변수 생성] 시간 데이터에서 어떤 변수를 새로 만들 수 있을까?

2019. 5. 6. 17:40분석 Python/구현 및 자료

728x90

현재 이런 식으로 시간이 관련된 정보가 있다고 하자.

이러한 시간을 다룰 때 나는 아직 경험이 부족해서 막막하게 느껴진다. 

머 두시간의 차이를 빼거나 아니면 사람별로 시간을 한개씩 shift(-1) (pandas)를 이용해서 빼서 이동 할 때 시간을 측정해본다던지, 여러가지로 시간을 잘 쓸 수 있을 것 같은데 아직 내공이 부족함을 느낀다.

 

## 기본적으로 뽑을 수 있는 정보들!

* year: 연도
* month: 월
* day: 일
* hour: 시
* minute: 분
* second: 초
* microsecond: 마이크로초(micro seconds, 백만분의 일초)

* weekday(): 요일 반환 (0:월, 1:화, 2:수, 3:목, 4:금, 5:토, 6:일)
* strftime(): 문자열 반환
* date(): 날짜 정보만 가지는 datetime.date 클래스 객체 반환
* time(): 시간 정보만 가지는 datetime.time 클래스 객체 반환

 

> map 과 lambda 을 이용해서 pandas에서 한번에 바꿔줄 수 있다

from datetime import datetime

year = lambda x: datetime.strptime(x, "%Y-%m-%d %H:%M:%S" ).year
day_of_week = lambda x: datetime.strptime(x, "%Y-%m-%d %H:%M:%S" ).weekday()
month = lambda x: datetime.strptime(x, "%Y-%m-%d %H:%M:%S" ).month
# please read docs on how week numbers are calculate
week_number = lambda x: datetime.strptime(x, "%Y-%m-%d %H:%M:%S" ).strftime('%V')

data['year'] = data['Date'].map(year)
data["day_of_week"] = data["Date"].map(day_of_week)
data["month"] = data["Date"].map(month)
data["week_number"] = data["Date"].map(week_number)
data.sample(10)

이렇게 하면 한 시간을 통해 기본적인 정보들을 모을 수 있다! 

좀 더 흥미로운 변수는 어떻게 만들 수 있을까?

  • season 별로 맵핑하기
  • 시간별로 의미 부여하기
    • 아래와 같이 시간 별로 어떠한 의미가 있다고 하고 부여하는 index를 주면 어떨까?

seasons = [0,0,1,1,1,2,2,2,3,3,3,0] 
season = lambda x: seasons[(datetime.strptime(x, "%Y-%m-%d %H:%M:%S" ).month-1)]

times_of_day = [0 , 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3,  4, 4, 4, 5, 5, 5 ]
time_of_day = lambda x: times_of_day[datetime.strptime(x, "%Y-%m-%d %H:%M:%S").hour]

data["season"] = data["Date"].map(season)
data["time_of_day"] = data["Date"].map(time_of_day)

시간에 따른 의미 부여 컬럼이 생겼다!

만약에 어떤 이벤트가 있다는 것을 알고 그 이벤트와 현재 있는 시간과의 관계를 보고 싶을 때 어떻게 하면 좋을까?

def compute_date_diff(x, y):
    # convert x into date, y into date, compute date diff
    date_x = datetime.strptime(x, "%Y-%m-%d %H:%M:%S" )
    date_y = datetime.strptime(y, "%Y-%m-%d %H:%M:%S")
    return (date_y - date_x).days
    
    
Certain_event = data["Another Date"][0:10].values.tolist()

for idx , i in enumerate(Certain_event) :
    data[ "diff" + str(idx) ] = data["Date"].apply(compute_date_diff , args = (i, ))

어떤 특정 이벤트와 얼마나 날짜가 떨어져 있는지를 알 수 있다!!

 

이처럼 시간이 의미있는 변수라고 했을 때 어떻게 하면 Feature Engineering을 할 수 있는지를 확인하였다.

데이터에 따라 의미는 달라지겠지만, 이런식의 접근을 하면 좀 더 유의미한 변수를 생성할 수 있을 것 같다.

 

참고한 글 : (개인적으로 위에 있는 설명도 좋다고 생각한다.)

https://towardsdatascience.com/feature-engineering-8ad1e532be07

 

Feature engineering

Feature engineering is the process of transforming raw, unprocessed data into a set of targeted features that best represent your…

towardsdatascience.com

 

728x90