728x90
반응형
시간데이터 조작¶
In [286]:
import pandas as pd
In [287]:
"""시간 유형 데이터 만들기"""
dates = ["2020-01-01","2020-03-01", "2021-09-01"]
dates
# 시간유형이어야만 날짜타입으로 바꿀 수 있다. / - .
Out[287]:
['2020-01-01', '2020-03-01', '2021-09-01']
In [288]:
"""시간 유형의 문자열을 날짜 타입으로 변환하기(형변환)"""
Out[288]:
'시간 유형의 문자열을 날짜 타입으로 변환하기(형변환)'
In [289]:
ts_dates= pd.to_datetime(dates)
ts_dates
Out[289]:
DatetimeIndex(['2020-01-01', '2020-03-01', '2021-09-01'], dtype='datetime64[ns]', freq=None)
In [290]:
ts_dates[0]
Out[290]:
Timestamp('2020-01-01 00:00:00')
In [291]:
type(ts_dates)
Out[291]:
pandas.core.indexes.datetimes.DatetimeIndex
In [292]:
"""년월일 단위로 추출하기
- to_period() : 날짜 타입의 데이터에서 특정 날짜(년,월,일)을 추출하고자 할 때사용
"""
pr_day = ts_dates.to_period(freq="d")
pr_day
Out[292]:
PeriodIndex(['2020-01-01', '2020-03-01', '2021-09-01'], dtype='period[D]')
In [293]:
"""년월 단위로 추출하기"""
pr_month = ts_dates.to_period(freq="m")
pr_month
Out[293]:
PeriodIndex(['2020-01', '2020-03', '2021-09'], dtype='period[M]')
In [294]:
"""년 단위로 추출하기"""
pr_year = ts_dates.to_period(freq="y")
pr_year
Out[294]:
PeriodIndex(['2020', '2020', '2021'], dtype='period[A-DEC]')
데이터 읽어 들이기¶
In [295]:
df= pd.read_csv("./data/timeseries.csv")
df
Out[295]:
Date | Close | Start | High | Low | Volume | |
---|---|---|---|---|---|---|
0 | 2015-07-02 | 10100 | 10850 | 10900 | 10000 | 137977 |
1 | 2016-06-29 | 10700 | 10550 | 10900 | 9990 | 170253 |
2 | 2017-06-28 | 10400 | 10900 | 10950 | 10150 | 155769 |
3 | 2018-06-27 | 10900 | 10800 | 11050 | 10500 | 133548 |
4 | 2019-06-26 | 10800 | 10900 | 11000 | 10700 | 63039 |
In [296]:
df.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 5 entries, 0 to 4 Data columns (total 6 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 Date 5 non-null object 1 Close 5 non-null int64 2 Start 5 non-null int64 3 High 5 non-null int64 4 Low 5 non-null int64 5 Volume 5 non-null int64 dtypes: int64(5), object(1) memory usage: 368.0+ bytes
In [297]:
"""
-Date 데이터를 날짜타입으로 변경하여
-새로운 칼럼에 넣어주세요
- 새로운 칼럼이름 : new_Date
"""
df["new_Date"]=pd.to_datetime(df["Date"])
In [298]:
df.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 5 entries, 0 to 4 Data columns (total 7 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 Date 5 non-null object 1 Close 5 non-null int64 2 Start 5 non-null int64 3 High 5 non-null int64 4 Low 5 non-null int64 5 Volume 5 non-null int64 6 new_Date 5 non-null datetime64[ns] dtypes: datetime64[ns](1), int64(5), object(1) memory usage: 408.0+ bytes
In [299]:
# new_Date 칼럼의 0번째 데이터 추출
df["new_Date"][0]
df.iloc[0,-1]
df.loc[0, "new_Date"]
df["new_Date"].loc[0] # index 상 순서
df["new_Date"].iloc[0] # 데이터 메모리상 순서
df["new_Date"].iloc[0].to_period(freq="Y") # 데이터 메모리상 순서
# 직접 메모리에 접근할때는 iloc, loc를 사용하여 수정하자
Out[299]:
Period('2015', 'A-DEC')
In [300]:
"""날짜 타입의 칼럼만 남기고 날짜 유형의 Data컬럼 삭제"""
# inplace=True 실제 메모리에 반영
df.drop("Date", axis=1, inplace=True)
In [301]:
df
Out[301]:
Close | Start | High | Low | Volume | new_Date | |
---|---|---|---|---|---|---|
0 | 10100 | 10850 | 10900 | 10000 | 137977 | 2015-07-02 |
1 | 10700 | 10550 | 10900 | 9990 | 170253 | 2016-06-29 |
2 | 10400 | 10900 | 10950 | 10150 | 155769 | 2017-06-28 |
3 | 10900 | 10800 | 11050 | 10500 | 133548 | 2018-06-27 |
4 | 10800 | 10900 | 11000 | 10700 | 63039 | 2019-06-26 |
In [302]:
"""
- 시계열 분석을 위해서는
-> index를 날짜 타입의 데이터로 사용해야함
- new_Date 칼럼의 데이터를 인덱스로 사용하게 해주십시오
"""
df.set_index("new_Date", inplace=True)
In [303]:
df
Out[303]:
Close | Start | High | Low | Volume | |
---|---|---|---|---|---|
new_Date | |||||
2015-07-02 | 10100 | 10850 | 10900 | 10000 | 137977 |
2016-06-29 | 10700 | 10550 | 10900 | 9990 | 170253 |
2017-06-28 | 10400 | 10900 | 10950 | 10150 | 155769 |
2018-06-27 | 10900 | 10800 | 11050 | 10500 | 133548 |
2019-06-26 | 10800 | 10900 | 11000 | 10700 | 63039 |
In [304]:
df.info()
<class 'pandas.core.frame.DataFrame'> DatetimeIndex: 5 entries, 2015-07-02 to 2019-06-26 Data columns (total 5 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 Close 5 non-null int64 1 Start 5 non-null int64 2 High 5 non-null int64 3 Low 5 non-null int64 4 Volume 5 non-null int64 dtypes: int64(5) memory usage: 240.0 bytes
기간 설정하기¶
In [305]:
"""
* 기간 설정하는 함수 : pd.date_range()
start: 설정 기간의 시작 값
end : 설정 기간의 끝값(None은 무한대)
periods: 생성할 기간의 갯수
freq: 시간 간격 설정( 숫자y 숫자m 숫자d)
tz:타입존 국가 설정
아래함수는
2020년 1월 1을 시작값으로 종료값 없이 6개의 구간값을 출력, 시간간격은 y년도를 기준으로 1씩증가 시키고
사용할 시간은 한국시간 사용
"""
timestamp_df = pd.date_range(start="2020-01-01",
end=None,
periods=6,
freq="1y",
tz="Asia/Seoul")
timestamp_df
Out[305]:
DatetimeIndex(['2020-12-31 00:00:00+09:00', '2021-12-31 00:00:00+09:00', '2022-12-31 00:00:00+09:00', '2023-12-31 00:00:00+09:00', '2024-12-31 00:00:00+09:00', '2025-12-31 00:00:00+09:00'], dtype='datetime64[ns, Asia/Seoul]', freq='A-DEC')
In [306]:
"""
3년단위로 기간구성하기
"""
timestamp_df2=pd.date_range(start="2020/01/01",
end=None,
periods=6,
freq="3y",
)
timestamp_df2
Out[306]:
DatetimeIndex(['2020-12-31', '2023-12-31', '2026-12-31', '2029-12-31', '2032-12-31', '2035-12-31'], dtype='datetime64[ns]', freq='3A-DEC')
In [307]:
"""
2개월 단위로 기간구성하기
"""
timestamp_df3= pd.date_range(start="2020/01/01",
end=None,
periods=3,
freq="2m",
)
timestamp_df3
Out[307]:
DatetimeIndex(['2020-01-31', '2020-03-31', '2020-05-31'], dtype='datetime64[ns]', freq='2M')
In [308]:
"""
3일 단위로 기간구성하기
"""
timestamp_df4= pd.date_range(start="2020/01/01",
end=None,
periods=6,
freq="3d",
)
timestamp_df4
Out[308]:
DatetimeIndex(['2020-01-01', '2020-01-04', '2020-01-07', '2020-01-10', '2020-01-13', '2020-01-16'], dtype='datetime64[ns]', freq='3D')
In [309]:
"""
2시간 단위로 기간구성하기
"""
timestamp_df5= pd.date_range(start="2020/01/01",
end=None,
periods=4,
freq="2h",
)
timestamp_df5
Out[309]:
DatetimeIndex(['2020-01-01 00:00:00', '2020-01-01 02:00:00', '2020-01-01 04:00:00', '2020-01-01 06:00:00'], dtype='datetime64[ns]', freq='2H')
In [310]:
"""
3분 단위로 기간구성하기
"""
timestamp_df6= pd.date_range(start="2020/01/01",
end=None,
periods=5,
freq="3min",
)
timestamp_df6
Out[310]:
DatetimeIndex(['2020-01-01 00:00:00', '2020-01-01 00:03:00', '2020-01-01 00:06:00', '2020-01-01 00:09:00', '2020-01-01 00:12:00'], dtype='datetime64[ns]', freq='3T')
In [311]:
"""
2초 단위로 기간구성하기
"""
timestamp_df7= pd.date_range(start="2020/01/01",
end=None,
periods=3,
freq="2s",
)
timestamp_df7
Out[311]:
DatetimeIndex(['2020-01-01 00:00:00', '2020-01-01 00:00:02', '2020-01-01 00:00:04'], dtype='datetime64[ns]', freq='2S')
In [312]:
"""
2일 2시간 2분 2초 간격으로 5개 기간을 추출
"""
timestamp_df8= pd.date_range(start="2020/01/01",
end=None,
periods=5,
freq="2d 2h 2min 2s",
)
timestamp_df8
Out[312]:
DatetimeIndex(['2020-01-01 00:00:00', '2020-01-03 02:02:02', '2020-01-05 04:04:04', '2020-01-07 06:06:06', '2020-01-09 08:08:08'], dtype='datetime64[ns]', freq='180122S')
In [313]:
df.reset_index(inplace=True)
In [314]:
"""new_Date 컬럼에서 년도만 추출하기
- 데이터 프레임 안에 특정 날짜 타입의 컬럼에서 각 값에서 년/월/일 추출/변경할 경우에는 각 값에 접근해야합니다.
"""
df["year"]=df["new_Date"].dt.year
In [315]:
"""new_Date 컬럼에서 월을 추출하기"""
df["month"]=df["new_Date"].dt.month
In [316]:
"""new_Date 컬럼에서 월을 추출하기"""
df["day"]=df["new_Date"].dt.day
In [317]:
df.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 5 entries, 0 to 4 Data columns (total 9 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 new_Date 5 non-null datetime64[ns] 1 Close 5 non-null int64 2 Start 5 non-null int64 3 High 5 non-null int64 4 Low 5 non-null int64 5 Volume 5 non-null int64 6 year 5 non-null int32 7 month 5 non-null int32 8 day 5 non-null int32 dtypes: datetime64[ns](1), int32(3), int64(5) memory usage: 428.0 bytes
In [318]:
"""new_Date 컬럼의 데이터를 이용해서
0000-00년월 단위로 추출하여 ym칼럼 생성하기"""
df["ym"]=df["new_Date"].dt.to_period(freq="M")
In [319]:
"""년-월-일 단위로 추출해섷 ymd 칼럼 생성하기"""
df["ymd"]=df["new_Date"].dt.to_period(freq="d")
df
# 시계열 데이터는 x 축에 시간 인덱스를 넣어야 하기에 원하는 형식의 시간 인덱스를 설정해주어야 한다.
Out[319]:
new_Date | Close | Start | High | Low | Volume | year | month | day | ym | ymd | |
---|---|---|---|---|---|---|---|---|---|---|---|
0 | 2015-07-02 | 10100 | 10850 | 10900 | 10000 | 137977 | 2015 | 7 | 2 | 2015-07 | 2015-07-02 |
1 | 2016-06-29 | 10700 | 10550 | 10900 | 9990 | 170253 | 2016 | 6 | 29 | 2016-06 | 2016-06-29 |
2 | 2017-06-28 | 10400 | 10900 | 10950 | 10150 | 155769 | 2017 | 6 | 28 | 2017-06 | 2017-06-28 |
3 | 2018-06-27 | 10900 | 10800 | 11050 | 10500 | 133548 | 2018 | 6 | 27 | 2018-06 | 2018-06-27 |
4 | 2019-06-26 | 10800 | 10900 | 11000 | 10700 | 63039 | 2019 | 6 | 26 | 2019-06 | 2019-06-26 |
In [320]:
df.set_index("new_Date",inplace=True)
df
Out[320]:
Close | Start | High | Low | Volume | year | month | day | ym | ymd | |
---|---|---|---|---|---|---|---|---|---|---|
new_Date | ||||||||||
2015-07-02 | 10100 | 10850 | 10900 | 10000 | 137977 | 2015 | 7 | 2 | 2015-07 | 2015-07-02 |
2016-06-29 | 10700 | 10550 | 10900 | 9990 | 170253 | 2016 | 6 | 29 | 2016-06 | 2016-06-29 |
2017-06-28 | 10400 | 10900 | 10950 | 10150 | 155769 | 2017 | 6 | 28 | 2017-06 | 2017-06-28 |
2018-06-27 | 10900 | 10800 | 11050 | 10500 | 133548 | 2018 | 6 | 27 | 2018-06 | 2018-06-27 |
2019-06-26 | 10800 | 10900 | 11000 | 10700 | 63039 | 2019 | 6 | 26 | 2019-06 | 2019-06-26 |
In [321]:
df.info()
<class 'pandas.core.frame.DataFrame'> DatetimeIndex: 5 entries, 2015-07-02 to 2019-06-26 Data columns (total 10 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 Close 5 non-null int64 1 Start 5 non-null int64 2 High 5 non-null int64 3 Low 5 non-null int64 4 Volume 5 non-null int64 5 year 5 non-null int32 6 month 5 non-null int32 7 day 5 non-null int32 8 ym 5 non-null period[M] 9 ymd 5 non-null period[D] dtypes: int32(3), int64(5), period[D](1), period[M](1) memory usage: 380.0 bytes
In [349]:
df
Out[349]:
Close | Start | High | Low | Volume | year | month | day | ym | ymd | |
---|---|---|---|---|---|---|---|---|---|---|
new_Date | ||||||||||
2015-07-02 | 10100 | 10850 | 10900 | 10000 | 137977 | 2015 | 7 | 2 | 2015-07 | 2015-07-02 |
2016-06-29 | 10700 | 10550 | 10900 | 9990 | 170253 | 2016 | 6 | 29 | 2016-06 | 2016-06-29 |
2017-06-28 | 10400 | 10900 | 10950 | 10150 | 155769 | 2017 | 6 | 28 | 2017-06 | 2017-06-28 |
2018-06-27 | 10900 | 10800 | 11050 | 10500 | 133548 | 2018 | 6 | 27 | 2018-06 | 2018-06-27 |
2019-06-26 | 10800 | 10900 | 11000 | 10700 | 63039 | 2019 | 6 | 26 | 2019-06 | 2019-06-26 |
In [355]:
"""df 데이터프레임의 0번째 행의 값을 추출해주세요"""
df.head(1)
df.iloc[0]
df.loc["2015-07-02"]
df[df.index==df.index[0]]
# df["2015-07-02"] 인덱스가 RangeINdex가 아니면 직접 접근이 안됨(오류 발생)
# lox 또는 iloc 사용해야함
Out[355]:
Close 10100 Start 10850 High 10900 Low 10000 Volume 137977 year 2015 month 7 day 2 ym 2015-07 ymd 2015-07-02 Name: 2015-07-02 00:00:00, dtype: object
In [373]:
df.iloc[1:4]
df.loc[["2016-06-29","2017-06-28", "2018-06-27"]]
df[df.index.isin([df.index[1], df.index[2], df.index[3]])]
Out[373]:
Close | Start | High | Low | Volume | year | month | day | ym | ymd | |
---|---|---|---|---|---|---|---|---|---|---|
new_Date | ||||||||||
2016-06-29 | 10700 | 10550 | 10900 | 9990 | 170253 | 2016 | 6 | 29 | 2016-06 | 2016-06-29 |
2017-06-28 | 10400 | 10900 | 10950 | 10150 | 155769 | 2017 | 6 | 28 | 2017-06 | 2017-06-28 |
2018-06-27 | 10900 | 10800 | 11050 | 10500 | 133548 | 2018 | 6 | 27 | 2018-06 | 2018-06-27 |
In [395]:
"""
df 변수로 csv 파일 새로 불러들이고
new_Date 칼럼 생성: Date컬럼을 날짜 타입으로 변환해서 사용
"""
df = pd.read_csv("./data/timeseries.csv")
df["new_Date"] = pd.to_datetime(df["Date"])
df.set_index("new_Date", inplace=True)
df.drop("Date", axis=1, inplace=True)
In [383]:
import matplotlib.pyplot as plt
In [396]:
df
Out[396]:
Close | Start | High | Low | Volume | |
---|---|---|---|---|---|
new_Date | |||||
2015-07-02 | 10100 | 10850 | 10900 | 10000 | 137977 |
2016-06-29 | 10700 | 10550 | 10900 | 9990 | 170253 |
2017-06-28 | 10400 | 10900 | 10950 | 10150 | 155769 |
2018-06-27 | 10900 | 10800 | 11050 | 10500 | 133548 |
2019-06-26 | 10800 | 10900 | 11000 | 10700 | 63039 |
In [412]:
"""
x축 값 인덱스 값
y축 각각 컬럼의 범위 값
각 컬럼에 대한 선그래프 그리기
-그래프 하나에 모든 컬럼의 선 그래프 표현
"""
plt.title("df")
plt.plot(df.index, df["Close"])
plt.plot(df.index, df["Start"])
plt.plot(df.index, df["High"])
plt.plot(df.index, df["Low"])
plt.plot(df.index, df["Volume"])
plt.grid()
plt.xlabel("YMD")
plt.ylabel("point")
plt.legend(df.columns)
plt.xticks(rotation=45)
plt.show()
In [ ]:
728x90
반응형
'파이썬' 카테고리의 다른 글
시계열 분석01 (1) | 2024.01.15 |
---|---|
다중회귀 모델 특성공학 (3) | 2023.12.21 |
머신러닝 기초 2 (3) | 2023.12.20 |
생선분류로 알아보는 머신러닝 (1) | 2023.12.20 |
머신러닝 기초 (3) | 2023.12.19 |