데이터 전처리 ( 시계열 )
시계열 데이터¶
- 시계열 데이터
- 시간의 흐름에 따라 데이터의 변화를 분석 및 예측하는데 사용되는 데이터
- 타임스탬프(timestamp) : 특정 시점(시간)을 의미하는 자료형
- 기능
- to_datetime : 데이터를 시간 자료형으로 변환시켜주는 함수
- to_period : 날짜 데이터의 년, 월, 일 등을 가져올 수 있다.
- 옵션
- freq를 이용하여 각각의 날짜 정보를 얻어올 수 있다
- freq = A(년), M(월), D(일)
- D지정시 2020-01-01까지 나오며, M지정시 2020-01, A지정시 2020까지 나온다.
- 옵션
- Datetimeindex자료형
- dt객체를 제공하며, dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second...등을 제공한다
- 자세한 정보는 다음 사이트를 참조하기 바란다.
- https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DatetimeIndex.html
In [1]:
import pandas as pd
dates = ['2021-01-01','2021-03-01','2021-05-01']
df = pd.DataFrame(dates, columns=['date'])
df
Out[1]:
date | |
---|---|
0 | 2021-01-01 |
1 | 2021-03-01 |
2 | 2021-05-01 |
In [3]:
# info() : 데이터 정보를 상세하게 출력
df.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 3 entries, 0 to 2 Data columns (total 1 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 date 3 non-null object dtypes: object(1) memory usage: 156.0+ bytes
In [5]:
# 기존에 있던 date 컬럼의 값(문자열로 저장되어 있는)을
# datetime 형식으로 변환하여 new_date 컬럼을 추가해서
# 거기에 데이터를 집어넣음
df['new_date'] = pd.to_datetime(df['date'])
df.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 3 entries, 0 to 2 Data columns (total 2 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 date 3 non-null object 1 new_date 3 non-null datetime64[ns] dtypes: datetime64[ns](1), object(1) memory usage: 180.0+ bytes
In [9]:
# datetime 은 각 년, 월, 일 을 뽑아서 사용할 수 있음
df['year'] = df['new_date'].dt.year
df['month'] = df['new_date'].dt.month
df['day'] = df['new_date'].dt.day
df
Out[9]:
date | new_date | year | month | day | |
---|---|---|---|---|---|
0 | 2021-01-01 | 2021-01-01 | 2021 | 1 | 1 |
1 | 2021-03-01 | 2021-03-01 | 2021 | 3 | 1 |
2 | 2021-05-01 | 2021-05-01 | 2021 | 5 | 1 |
In [11]:
# 새로운 Dataset 추가
dates = [1,2,3]
df = pd.DataFrame(dates, columns=['date'])
df
Out[11]:
date | |
---|---|
0 | 1 |
1 | 2 |
2 | 3 |
In [14]:
for i in df['date']:
print(i * 10)
10 20 30
In [16]:
# lambda 를 사용
# x 에 각 테이터가 매개변수로 들어가며
# x 값 * 10 의 값을 return 으로 가지고 나온다
df['date'] = df['date'].apply( lambda x : x*10 )
df
Out[16]:
date | |
---|---|
0 | 100 |
1 | 200 |
2 | 300 |
In [37]:
# 새로운 Dataset 추가
dates = ['2021-01-01','2021-03-01','2021-05-01']
df = pd.DataFrame(dates, columns=['date'])
df
Out[37]:
date | |
---|---|
0 | 2021-01-01 |
1 | 2021-03-01 |
2 | 2021-05-01 |
In [19]:
df.dtypes
Out[19]:
date object dtype: object
In [38]:
# date 컬럼의 전체 값을 datetime 자료형으로 변환하여 date 변수에 저장
date = df['date'].apply( lambda x : pd.to_datetime(x) )
date
Out[38]:
0 2021-01-01 1 2021-03-01 2 2021-05-01 Name: date, dtype: datetime64[ns]
In [39]:
# 요일은 dayofweek 으로 표현 ( 0:월 ~ 6:일 까지 숫자로 변환 )
df['year'] = date.apply( lambda x : x.year )
df['month'] = date.apply( lambda x : x.month )
df['day'] = date.apply( lambda x : x.day )
df['요일'] = date.apply( lambda x : x.dayofweek )
df
Out[39]:
date | year | month | day | 요일 | |
---|---|---|---|---|---|
0 | 2021-01-01 | 2021 | 1 | 1 | 4 |
1 | 2021-03-01 | 2021 | 3 | 1 | 0 |
2 | 2021-05-01 | 2021 | 5 | 1 | 5 |
In [40]:
# x 에 대입된 값이 2보다 크면 1111 return
df['month'] = df['month'].apply ( lambda x : 1111 if x > 2 else x )
df
Out[40]:
date | year | month | day | 요일 | |
---|---|---|---|---|---|
0 | 2021-01-01 | 2021 | 1 | 1 | 4 |
1 | 2021-03-01 | 2021 | 1111 | 1 | 0 |
2 | 2021-05-01 | 2021 | 1111 | 1 | 5 |
In [41]:
# 자기 자신에게 데이터 저장이 불가함... loc 를 사용해야 한다
df[ ( df['year'] == 2021 ) & ( df['month'] == 1111 ) ]['요일'] = \
df[ ( df['year'] == 2021 ) & ( df['month'] == 1111 ) ]['요일'].apply ( lambda x : 1111 if x > 2 else x )
df
C:\Users\user\AppData\Local\Temp\ipykernel_11252\104542716.py:2: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy df[ ( df['year'] == 2021 ) & ( df['month'] == 1111 ) ]['요일'] = \
Out[41]:
date | year | month | day | 요일 | |
---|---|---|---|---|---|
0 | 2021-01-01 | 2021 | 1 | 1 | 4 |
1 | 2021-03-01 | 2021 | 1111 | 1 | 0 |
2 | 2021-05-01 | 2021 | 1111 | 1 | 5 |
In [42]:
# loc 를 활용하여 데이터를 저장
df.loc[ ( df['year'] == 2021 ) & ( df['month'] == 1111 ), '요일'] = \
df[ ( df['year'] == 2021 ) & ( df['month'] == 1111 ) ]['요일'].apply ( lambda x : 1111 if x > 2 else x )
df
Out[42]:
date | year | month | day | 요일 | |
---|---|---|---|---|---|
0 | 2021-01-01 | 2021 | 1 | 1 | 4 |
1 | 2021-03-01 | 2021 | 1111 | 1 | 0 |
2 | 2021-05-01 | 2021 | 1111 | 1 | 1111 |
In [45]:
df_test = df[['date', 'year']]
df_test
Out[45]:
date | year | |
---|---|---|
0 | 2021-01-01 | 2021 |
1 | 2021-03-01 | 2021 |
2 | 2021-05-01 | 2021 |
In [46]:
# dataframe 안의 값을 dictionary 자료형으로 변경해준다
# 키와 값으로 매칭
df_test = df_test.to_dict("list")
df_test
Out[46]:
{'date': ['2021-01-01', '2021-03-01', '2021-05-01'], 'year': [2021, 2021, 2021]}
In [48]:
df_test['date']
Out[48]:
['2021-01-01', '2021-03-01', '2021-05-01']
In [49]:
df_test['date'][0]
Out[49]:
'2021-01-01'
In [51]:
df_date = df_test['date']
df_year = df_test['year']
print( len(df_date) ) # 길이 확인
for i in range( len(df_date) ):
print( df_date[i], " : ", df_year[i] )
3 2021-01-01 : 2021 2021-03-01 : 2021 2021-05-01 : 2021
728x90
'BE > 머신러닝(ML)' 카테고리의 다른 글
[머신러닝] 실습 예제 및 풀이 (1) | 2024.05.23 |
---|---|
[머신러닝] 데이터 전처리 ( 그룹 ) (0) | 2024.05.23 |
[머신러닝] 데이터 전처리 ( 원 핫 인코딩 ) (0) | 2024.05.23 |
[머신러닝] 모델 생성 및 평가 (0) | 2024.05.23 |
[머신러닝] 데이터 전처리 ( 이상치, 중복 데이터, 문자 데이터 ) (0) | 2024.05.23 |