시카고의 범죄 발생 시각을 기록한 데이터가 있다.
이 데이터로 prophet 라이브러리를 사용해 미래에 범죄가 얼마나 발생할지 예측하려 한다.
prophet 참고: https://donghyeok90.tistory.com/190
Prophet 라이브러리를 사용한 Time Series(시계열) 데이터 예측
1. Prophet 라이브러리 페이스북이 개발한 일변량(하나의 변수) 시계열 예측을 위한 오픈소스 라이브러리 경향성(Trends), 계절성(seosonality), 휴일(holidays)을 반영하는 모델이다. 계절적 효과가 강하고
donghyeok90.tistory.com
groupby 함수를 이용해서는 날짜데이터를 년단위, 월단위, 일단위 등으로 그룹화 할 수 없다.
날짜 단위로 그룹화하기 위해 pandas.DataFrame.resample 메소드를 사용해보자.
1. pandas.DataFrame.resample()
Datetime Index를 원하는 주기로 나누어주는 메소드. 이러한 방식을 리샘플링이라고 한다.
df.resample(rule, axis=0, closed=None, label=None, convention='start', kind=None,
on=None, level=None, origin='start_day', offset=None)
- rule : 리샘플링 할 기준. 단위로는 Y, M, D, H, T(min), S ... 등을 조합하여 사용할 수 있다.
- on : 인덱스가 아닌 열 기준으로 리샘플링을 시도할 경우, 해당 열의 이름을 지정하는 인수.
- 다른 파라미터 사용법 참고: https://wikidocs.net/158101
2. prophet을 사용할 수 있게 데이터 가공
# 년도별 범죄횟수
# 년도별로 그룹화하고 각 그룹의 갯수를 구한다.
df_year = chicago_df.resample('Y', on='Date').size()
# 리샘플링한 Date가 인덱스로 가기 때문에 reset_index 해준다.
df_year = df_year.reset_index()
# prophet 사용법에 맞게 컬럼명 변경
df_year.columns = ['ds', 'y']
# 월별 범죄횟수
df_month = chicago_df.resample('M', on='Date').size()
df_month = df_month.reset_index()
df_month.columns = ['ds', 'y']
# 일별 범죄횟수
df_day = chicago_df.resample('D', on='Date').size()
df_day = df_day.reset_index()
df_day.columns = ['ds', 'y']
'Python > Pandas' 카테고리의 다른 글
Numpy/Pandas 에서 datetime 다루기 (0) | 2022.12.02 |
---|---|
Pandas 데이터프레임에서 boolean indexing의 활용 (0) | 2022.12.01 |
Pandas 피벗 테이블(Pivot table) (0) | 2022.12.01 |
오픈API Goolglemaps Geocode로 위치정보 받아오기 (0) | 2022.12.01 |
Pandas의 DataFrame.plot() 으로 시각화하기 (0) | 2022.12.01 |