# dasos['Date'] = pd.to_datetime(dasos['Date'], format='%Y-%m-%d %H:%M:%S')
# dasos.head()
연구 노트/R Python
- 날짜 형식 변환 2022.03.11
- 인덱스 추출법 2022.03.11
- 같은 값을 가지는 행들끼리 이어붙이기 (링크) 2022.02.16
- datetime 변환 오류 24:00를 00:00 으로 바꿔야 ... 2022.02.15
- 파이썬 문자열 처리를 위한 다양한 메소드 (Python string methods) (링크) 2022.02.14
- [링크] 태양광 계산법 (이론) 2022.02.04
- 연속 열 누락 데이터 처리 방법 및 구현 2022.01.21
- 파이썬 보간법을 이용한 결측치 넣기 2022.01.21
- scaler 스케일 변환시 주의사항 2022.01.21
- reset_index()['Tair'] 2022.01.20
- 가중치 Weights를 출력하는 방법 2022.01.20
- ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 100, 1), found shape=(None, 21) 2022.01.20
- Importance 바차트 출력 2022.01.17
- GridSearchCV 평가 - 최적 파라미터 출력 2022.01.17
- def roc_curve_plot() 함수 코드 2022.01.17
- def get_clf_eval() 함수 코드 2022.01.17
- 시계열 데이터 - 슬라이더로 살펴보기 2022.01.14
- 모델 저장 및 불러오기 2022.01.11
- AttributeError: Can only use .dt accessor with datetimelike values 2022.01.07
- graphviz 사용법 (링크) 2021.12.28
날짜 형식 변환
인덱스 추출법
# ind_sub = df['NO2'].loc[(df['Date'] >= '2019-11-13 16:00:00') & (df['Date'] <= '2020-02-14 13:00:00')].index.tolist()
# # ind_sub
같은 값을 가지는 행들끼리 이어붙이기 (링크)
datetime 변환 오류 24:00를 00:00 으로 바꿔야 ...
에러:
24:00 로 시간이 표시되면 에러 발생
23:00 로 바꾸고, 날짜 바꾸고 월, 년 다 바꿔야 함.
아래 와 같이 해결
코드:
from datetime import timedelta
import pandas as pd
df['datetime_zero'] = df['Datetime'].str.replace('24:00', '00:00')
df['datetime_er'] = pd.to_datetime(df['datetime_zero'], format='%Y-%m-%d %H:%M:%S')
selrow = df['Datetime'].str.contains('24:00')
df['datetime_obj'] = df['datetime_er'] + selrow * timedelta(days=1)
ValueError: time data '10/11/2006 24:00' does not match format '%d/%m/%Y %H:%M'
I tried: df["datetime_obj"] = df["datetime"].apply(lambda dt: datetime.strptime(dt, "%d/%m/%Y %H:%M")) but got this error: ValueError: time data '10/11/2006 24:00' does not match format '%d/...
stackoverflow.com
https://kkwor1d.tistory.com/39?category=986286
[에러해결] datetime | hour 24:00:00 변환 오류
Problem with converting to 'datetime' type: ValueError: hour must be in 0..23. [문제] 시계열 자료에서 시간 데이터는 datetime 처리 후 작업을 하는데, 간혹 데이터 중에 시간 부분이 '24시'로 표현되어 있..
kkwor1d.tistory.com
파이썬 문자열 처리를 위한 다양한 메소드 (Python string methods) (링크)
[링크] 태양광 계산법 (이론)
연속 열 누락 데이터 처리 방법 및 구현
파이썬 보간법을 이용한 결측치 넣기
scaler 스케일 변환시 주의사항
학습/테스트 데이터의 스케일 변환시 주의사항
MinMaxScaler 객체의 fit( ) 과 transform( )
이 둘은 2차원 데이터만 가능하므로 reshape(-1, 1)로 차원 변경해야 한다.
train_array = np.arrange(0, 11).reshape(-1,1)
test_array = np.arrange(0, 6).reshape(-1,1)
fit( ) 의 경우 [0,10] 스케일이 적용됨.
일반적으로 fit_transform( )을 사용하여 학습데이터와 테스트 데이터 스케일을 변환한다. 이는 fit( )과 transform( )을 순차적으로 수행하는 메소드이다.
학습데이터에서는 상관없지만, 테스트 데이터에서는 fit_transform( )을 절대 사용해서는 안된다.
따라서, 정확히 사용하려면, 학습과 테스트 데이터를 분리하기 전에 스케일링을 적용하고 분리해야 한다.
이 주의사항은 차원축소변환, 피쳐벡터화 변화 작업에도 동일하게 적용된다.
reset_index()['Tair']
df = dd.reset_index()['Tair']
가중치 Weights를 출력하는 방법
ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 100, 1), found shape=(None, 21)
LSTM 다룰 때 중요한 부분!
에러
ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 100, 1), found shape=(None, 21)
원인
LSTM 모델을 사용할 때는, train 차원을 바꾸어야 하는데, 차원 변경을 해 주지 않으면 발생하는 에러
해결
X_train = X_train.reshape(X_train.shape[0], X_train[1], 1)
명령으로 2차원 데이터를 3차원으로 변경하면 됨.
Importance 바차트 출력
코드
ftr_importances_values = model.feature_importances_
ftr_importances = pd.Series(ftr_importances_values)#, index=X_train.columns)
ftr_top20 = ftr_importances.sort_values(ascending=False)[:20]
plt.figure(figsize=(15,6))
sns.barplot(x=ftr_top20, y=ftr_top20.index)
# plt.show()
GridSearchCV 평가 - 최적 파라미터 출력
코드
from sklearn.model_selection import GridSearchCV
params = {
'n_estimators':[100],
'max_depth' : [6,8,10.,12],
'min_samples_leaf' : [8,12, 18],
'min_samples_split' : [8,16, 20]
}
rf_clf = RandomForestClassifier(random_state=0)
model = rf_clf
grid_cv = GridSearchCV(model, param_grid=params, cv=2, n_jobs=-1)
grid_cv.fit(X_train, y_train)
print('Best parameter:\n', grid_cv.best_params_)
print('Highest accuracy: {0:.4f}'.format(grid_cv.best_score_))
출처: 파이썬 머신러닝 완벽가이드 p220
def roc_curve_plot() 함수 코드
def roc_curve_plot(y_test, pred_proba_c1):
fprs, tprs, thresholds = roc_curve(y_test, pred_proba_c1)
plt.plot(fprs, tprs, label='ROC')
plt.plot([0,1], [0,1], 'k--', label='Random')
start, end = plt.xlim()
plt.xticks(np.round(np.arange(start, end, 0.1), 2))
plt.xlim(0,1);plt.ylim(0,1)
plt.xlabel('FPR( 1 - sensitivity )'); plt.ylabel('TPR( Recall )')
plt.legend()
def get_clf_eval() 함수 코드
from sklearn.metrics import accuracy_score, precision_score, recall_score, confusion_matrix, f1_score, roc_auc_score
from sklearn.metrics import roc_curve
def get_clf_eval(y_test, pred=None, pred_proba=None):
confusion = confusion_matrix(y_test, pred)
accuracy= accuracy_socre(y_test, pred)
precision = precision_score(y_test, pred)
recall = recall_score(y_test, pred)
f1 = f1_score(y_test, pred)
roc_auc = roc_auc_score(y_test, pred_proba)
print('error matrix')
print(confusion)
print('Accu : {0:.4f}, Prec : {1:.4f}, Recu : {2:.4f},\
F1 : {3:.4f}, AUC : {4:.4f}'.format(accuracy, precision, recall, f1, roc_auc))
시계열 데이터 - 슬라이더로 살펴보기
전처리 과정에서, 시계열 데이터를 살펴볼때 아래와 같이 slider 를 사용하면 missing-data 를 찾거나, 경향성 파악에 크게 도움이 된다.
코드
df.reset_index(inplace=True)
import plotly.express as px
fig=px.line(df, x='Date', y='Tair_C', title='Tair_Cm with slider')
fig.update_xaxes(
rangeslider_visible=True,
rangeselector=dict(
buttons=list([
dict(count=1, label="1m", step="month", stepmode="backward"),
dict(count=2, label="3m", step="month", stepmode="backward"),
dict(count=2, label="6m", step="month", stepmode="backward"),
dict(step="all")]
)
)
)
fig.show()
모델 저장 및 불러오기
AttributeError: Can only use .dt accessor with datetimelike values
datetime 변환 코드 상에서 이와 같은 에러가 발생
pandas 데이터 인식이 잘 못된 경우일 수 있다. 아래와 같이 설정
train["datetime"] = pd.to_datetime(train["datetime"])
.dt에서 어트리뷰트 에러발생 - 인프런 | 질문 & 답변 (inflearn.com)
.dt에서 어트리뷰트 에러발생 - 인프런 | 질문 & 답변
train['year'] = train['datetime'].dt.year train['month'] = train['datetime'].dt.month train['day'] = train['datetime'].dt.day train['hour'] = train['...
www.inflearn.com