▶ pd.date_range()
- start : 시작 날짜
- periods : 생성할 timestamp 개수
- freq : 시간 간격
(D: 1일 간격(기본값), nD: n일, w: 1주, M: 월말, MS: 월초, Q: 분기말, QS : 분기초, A:연말, AS: 연초)
# 기본값인 1일 간격으로 6개의 타임스탬프 생성
dates = pd.date_range('20231110', periods=6)
print(type(dates))
print(dates)
<class 'pandas.core.indexes.datetimes.DatetimeIndex'>
DatetimeIndex(['2023-11-10', '2023-11-11', '2023-11-12', '2023-11-13',
'2023-11-14', '2023-11-15'],
dtype='datetime64[ns]', freq='D')
# 월초를 기준으로 6개의 타임스탬프 생성 (5월은 월초를 지났기 때문에 다가오는 가장 이른 월초인 6월을 시작값으로 함)
dates = pd.date_range('20230508', periods=6, freq='MS')
print(dates)
DatetimeIndex(['2023-06-01', '2023-07-01', '2023-08-01', '2023-09-01',
'2023-10-01', '2023-11-01'],
dtype='datetime64[ns]', freq='MS')
Click to add a cell.
▶ pd.to_datetime()
- 문자열 등 다른 자료형을 판다스 timestamp를 나타내는 datetime64 자료형으로 변환 한다.
import pandas as pd
date_list = ['2023-01-01', '2023-02-01', '2023-03-01']
ts_date = pd.to_datetime(date_list)
print(ts_date)
DatetimeIndex(['2023-01-01', '2023-02-01', '2023-03-01'], dtype='datetime64[ns]', freq=None)
※ 필요한 날짜와 시간 찾기
# 연도 정보만 출력
print(ts_date.year)
# 월 정보만 출력
print(ts_date.month)
# 요일 정보만 출력 (6=일요일, 2=수요일)
print(ts_date.dayofweek)
Index([2023, 2023, 2023], dtype='int32')
Index([1, 2, 3], dtype='int32')
Index([6, 2, 2], dtype='int32')
▶ dt 속성
- datetime 타입으로 변환된 column(datetime 타입의 Series 객체)에서 날짜 및 시간 정보를 추출하고 싶은 경우에는 dt 속성을 이용해야 한다.
df = pd.DataFrame(
{'날짜':['2023-01-01','2023-02-01','2023-03-01'],
'매출':[1000,2000,3000]}
)
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 날짜 3 non-null object
1 매출 3 non-null int64
dtypes: int64(1), object(1)
memory usage: 180.0+ bytes
# 날짜 type 변경 (object -> datetime64)
df['날짜'] = pd.to_datetime(df['날짜'])
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 날짜 3 non-null datetime64[ns]
1 매출 3 non-null int64
dtypes: datetime64[ns](1), int64(1)
memory usage: 180.0 bytes
# 하나의 컬럼값은 Series 객체로 넘어옴 (datetime 속성을 바로 사용할 수 없음)
# df['날짜'].year 에러 발생
# dt속성 사용
df['날짜'].dt.year
0 2023
1 2023
2 2023
Name: 날짜, dtype: int32
# 1월에 해당하는 매출 정보만 가져옴
df[df['날짜'].dt.month == 1]
▶ to_datetime()의 format
- format 속성은 지정한 format으로 변경하라는 의미가 아닌, 원본 데이터를 주어진 format에 맞춰 해석하여 변경하라는 의미
- format 형식 참고 : https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior
datetime — Basic date and time types
Source code: Lib/datetime.py The datetime module supplies classes for manipulating dates and times. While date and time arithmetic is supported, the focus of the implementation is on efficient attr...
docs.python.org
values = {'dates':['05032023','16032023','28032023'],
'status':['Opened','Opened','Closed']}
df = pd.DataFrame(values)
# 별도의 포맷을 지정해주지 않으면 에러 발생 (앞의 4자리를 년으로 인식)
# df['dates'] = pd.to_datetime(df['dates'])
# 포맷을 %d%m%Y로 변경
df['dates'] = pd.to_datetime(df['dates'], format='%d%m%Y')
df.info()
df
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 dates 3 non-null datetime64[ns]
1 status 3 non-null object
dtypes: datetime64[ns](1), object(1)
memory usage: 180.0+ bytes
values = {'dates':['05Mar2023','16Mar2023','28Mar2023'],
'status':['Opened','Opened','Closed']}
df = pd.DataFrame(values)
# 월이 문자형태로 되어있을 경우 %b로 변경
df['dates'] = pd.to_datetime(df['dates'], format='%d%b%Y')
df.info()
df
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 dates 3 non-null datetime64[ns]
1 status 3 non-null object
dtypes: datetime64[ns](1), object(1)
memory usage: 180.0+ bytes
values = {'dates':['20230305093000','20230316102520','20230328012015'],
'status':['Opened','Opened','Closed']}
df = pd.DataFrame(values)
# 날짜 형식 년월일시분초 (%Y%m%d%H%M%S)
df['dates'] = pd.to_datetime(df['dates'], format='%Y%m%d%H%M%S')
df.info()
df
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 dates 3 non-null datetime64[ns]
1 status 3 non-null object
dtypes: datetime64[ns](1), object(1)
memory usage: 180.0+ bytes
▶ to_period()
- DatetimeIndex 객체를 PeriodIndex 객체로 변환
- freq : 변경하고자 하는 시간 간격
date_list = ['2023-01-01', '2023-02-01', '2023-03-01']
ts_date = pd.to_datetime(date_list)
print(ts_date)
DatetimeIndex(['2023-01-01', '2023-02-01', '2023-03-01'], dtype='datetime64[ns]', freq=None)
# 주 간격으로 변환
# 원본 날짜를 포함하는 월~일요일까지의 주 간격 날짜 데이터 생성
# 2023-01-01 -> 같은 주에 있는 원요일 2022-12-26 부터 일요일 2023-01-01까지
ps = ts_date.to_period(freq='W')
print(ps)
PeriodIndex(['2022-12-26/2023-01-01', '2023-01-30/2023-02-05',
'2023-02-27/2023-03-05'],
dtype='period[W-SUN]')
# 월 간격으로 변환
ps = ts_date.to_period(freq='M')
print(ps)
PeriodIndex(['2023-01', '2023-02', '2023-03'], dtype='period[M]')
'데이터 분석 > 판다스' 카테고리의 다른 글
[Pandas] 국가별 알콜 섭취량 데이터 분석 (0) | 2023.11.13 |
---|---|
[Pandas] 시애틀 강수량 데이터 분석 (0) | 2023.11.13 |
[Pandas] DataFrame 합치기 (0) | 2023.11.13 |
[Pandas] 함수 매핑 (0) | 2023.11.13 |
[Pandas] 개요 (0) | 2023.11.09 |