pandas : TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Index'
pandas 에러 처리
TypeError: Only valid with DatetimeIndex,
TimedeltaIndex or PeriodIndex, but got an instance of 'Index'
기계학습 실험을 하기 위해 그냥 평상시처럼 csv 파일을 아래와 같이 읽어왔다.
rawdata = pd.read_csv("/data/training.csv", parse_dates =["date"], index_col ="date", sep='\t', encoding='utf-8')
필드별 통계를 보기위해 resample을 했는데 아래와 같은 에러가 발생하는 것이다?!
pandas : TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Index'
resample을 하기위해서는 datetimeindex가 있어야하는데 index만 있다는 것이다.
csv 읽어올때 parse_dates 옵션을 줬는데도 info를 확인해보니 datetimeindex가 아닌 index로 걸려있었다.
nan을 보니 빈문자열이 있는 것 같아서 삭제했는데도 index만 걸려있다.
to_datetime 함수로 명확하게 필드 타입 변환을 해보기로 했다.
에러를 확인해야하니 errors='raise'로 설정하였다.
ds['date'] = pd.to_datetime(rawdata['date'].str.strip(), format='%Y-%m-%d', errors='raise')
아래 date라는 필드명과 에러가 나는 문자열 이름이 같아서 좀 헷갈렸는데
date라는 문자열이 해당 date 필드에 들어있어서 문자열 변환에서 오류가 난 것이다.
중간에 컬럼명이 한번 더 들어간 모양이다.
ValueError: time data u'date' does match format specified
이렇게 해서 해결! 인 줄 알았는데 아래와 같이 이상한 문자열 에러는 계속 나왔다 ㅠㅠ
정부 open API로 데이터를 수집한 것은 좋은데 검증은 안하고 그냥 데이터 보내나 보다 ㅠㅠ
time data u'0973-04-12' does match format specified
ValueError: time data u'9187-06-08' does match format specified
ValueError: time data u'0999-09-08' does match format specified
time data u'1669-09-11' does match format specified
위 문자열까지 해결하니 제대로 datetimeindex 걸린것을 확인할 수 있었다.
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 102918 entries, 1960-12-17 to 2020-06-23
Data columns (total 36 columns):
opnSvcNm 102918 non-null object