주식, 환율 등의 금융 데이터를 다루기 위해 개발된 판다스는 시계열(time series) 데이터를 여러 가지 유용한 기능을 제공한다. 특히 시계열 데이터를 데이터프렝미의 행 인덱스로 사용하면, 시간으로 기록된 데이터를 분석하는 것이 매우 편리하다.
판다스의 시간 표시 방식 중에서 시계열 데이터 표현에 자주 이용되는 두 가지 유형이 있다.
많은 시간 데이터들은 별도의 시간 자료형으로 기록 되지 않고, 문자열이나 시간으로 저장되는 경우가 많다. 이를 변환해보자.
아래와 같이 날짜가 문자열로 되어있는 파일의 날짜를 Timestamp객체로 변환시켜보자.
Date Close Start High Low Volume
0 2018-07-02 10100 10850 10900 10000 137977
1 2018-06-29 10700 10550 10900 9990 170253
2 2018-06-28 10400 10900 10950 10150 155769
3 2018-06-27 10900 10800 11050 10500 133548
4 2018-06-26 10800 10900 11000 10700 63039
to_datetime() 함수는 문자열(objec) 데이터를 datetime64 자료형으로 변환한다.
import pandas as pd
df = pd.read_csv('stock-data.csv')
df['new date'] = pd.to_datetime(df['Date'])
print(df.info())
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 20 entries, 0 to 19
Data columns (total 7 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Date 20 non-null object
1 Close 20 non-null int64
2 Start 20 non-null int64
3 High 20 non-null int64
4 Low 20 non-null int64
5 Volume 20 non-null int64
6 new date 20 non-null datetime64[ns]
dtypes: datetime64[ns](1), int64(5), object(1)
memory usage: 1.2+ KB
None
'Date'행을 제거하고 'new date'열을 행 인덱스로 설정해보자. 시계열 데이터를 인덱스로 지정하면 판다스는 DatetimeIndex로 지정한다.
import pandas as pd
df = pd.read_csv('stock-data.csv')
df['new_date'] = pd.to_datetime(df['Date'])
df.drop('Date', axis=1, inplace=True)
df.set_index('new_date', inplace=True)
print(df.head())
print(df.info())
Close Start High Low Volume
new_date
2018-07-02 10100 10850 10900 10000 137977
2018-06-29 10700 10550 10900 9990 170253
2018-06-28 10400 10900 10950 10150 155769
2018-06-27 10900 10800 11050 10500 133548
2018-06-26 10800 10900 11000 10700 63039
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 20 entries, 2018-07-02 to 2018-06-01
Data columns (total 5 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Close 20 non-null int64
1 Start 20 non-null int64
2 High 20 non-null int64
3 Low 20 non-null int64
4 Volume 20 non-null int64
dtypes: int64(5)
memory usage: 960.0 bytes
None
to_period() 함수를 이용하면 Timestamp객체를 Period로 변환할 수 있다. freq옵션에서 기준이 되는 기간을 설정한다.
import pandas as pd
dates = ['2019-01-01', '2020-03-01', '2021-06-01']
ts_dates = pd.to_datetime(dates)
print(ts_dates)
print()
# Timestamp -> Period
pr_day = ts_dates.to_period(freq='D')
print(pr_day)
print()
pr_month = ts_dates.to_period(freq='M')
print(pr_month)
print()
pr_year = ts_dates.to_period(freq='Y')
print(pr_year)