transform(): 그룹 기반 함수 적용, 새로운 열 생성
map(): 벡터화된 함수 적용, 원본 열 변경
apply(): 축 기반 함수 적용, 다양한 결과 형식 가능
6. 선택 가이드:
그룹별 집계 또는 변환: transform()
벡터화된 함수 적용: map()
행 또는 열 기반 함수 적용: apply()
df.shape()
df.isnull().sum()
len(df['col'].unique())
df.replace(-200,np.NaN) ## 특정값 치환
df.fillna(method='ffill') ## frontfill
np.where(df['col'] <= 5, 1, 0) ## 특정 조건 값 변경하기
df[df['col'].astype(str).str.contains('text')]
pd.pivot_table(df_job, index='index', columns='col', values='value')
df.replace([np.inf, -np.inf], np.nan) ## 무한대 null 처리
##lag 데이터 생성 +n : 순방향 , -n 역방향
df['col'].shift(1)
##문자열 데이터 앞 공백제거
df['col'].str.lstrip()
##날짜 데이터 형식 변경
import datetime
df["Date"].dt.strftime("%Y-%m")
##list 중복 없애기
all_list = list(df['start']) + list(df['end'])
unique_list = set(all_list)
sns.displot(df['col']) # displot 활용 분포 그리기
print("col :", df['col'].mean()) #분포의 기술 통계도 같이 출력
plt.gcf().set_size_inches(20,5)
import seaborn as sns
sns.scatterplot(x=df['x'], y=df['y'], hue=df['hue'], data=df)
import matplotlib.pyplot as plt
plt.plot(df['x'], df['y'], label='label')
for i in range(1,13):
plt.subplot(3,4,i)
plt.grid(False)
sns.displot(df.iloc[:,i])
plt.tight_layout()
plt.show()
df_pair = df[['col1' ~ ]] ## 변수 추리기
sns.pairplot(df_pair)
sns.heatmap(df_pair.corr(), vmin=-1, vmax=+1, annot = Ture, cmap='coolwarm')
plt.vlines(2, ymin=-2, ymax=2, color='r', linewidth=2)
plt.hlines
sns.catplot(x='x', hue='y', kind='count', palette='pastel', data=df)
df['vol_color'] =np.where(df['Volume_issue']==1, 'red', 'gray')
colors= list(df['vol_color'])
plt.bar(df['Date'], df['Volume'], label='volume', color=colors)
빈껍데기 만들기
rfc = RandomForestClassifier(random_state=123456)
모델 학습시키기
rfc.fit(x_train, y_train)
예측, 학습에 사용된 Data와 test data 모두 예측하고 평가(★★과적합 여부 판별)
y_pred_train = rfc(위에서 학습시킨).predict(x_train)
y_pred_test = rfc.predict(x_test)
이진 분류 모델 성능 확인
from sklearn.metrics import classification_report
classification_report(y_train, y_pred_train))
classification_report(y_test, y_pred_test))
하이퍼파라미터 튜닝
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import GridSearchCV
params = { 'n_estimators' : [400, 500],
'max_depth' : [6, 8, 10, 12]
}
# RandomForestClassifier 객체 생성 후 GridSearchCV 수행
rf_clf = RandomForestClassifier(random_state = 123456, n_jobs = -1)
grid_cv = GridSearchCV(rf_clf, param_grid = params, cv = 3, n_jobs = -1, scoring='recall')
grid_cv.fit(x_train, y_train)
print('최적 하이퍼 파라미터: ', grid_cv.best_params_)
print('최고 예측 정확도: {:.4f}'.format(grid_cv.best_score_))
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
plt.style.use(['dark_background'])
# rfc → 생성한 Model에 name 기재
ftr_importances_values = rfc.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=(8,6))
plt.title('Feature Importances')
sns.barplot(x=ftr_top20, y=ftr_top20.index)
plt.show()
import pickle
# 모델 저장
saved_model = pickle.dumps(model)
# 모델 Read
model_from_pickle = pickle.loads(saved_model)
import scipy.stats as stats
stats.pearsonr(x=df['x'], y=df['y'])
앞에는 비슷하다.
# 모델링을 학습하기 위한 Fearue(X)와 Y데이터를 구분하는 단계
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn import metrics
X=df.drop(['y'], axis=1)
Y=df['y']
x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size=0.3)
print(x_train.shape)
print(y_train.shape)
print(x_test.shape)
print(y_test.shape)
# RandomForestRegressor 모델 학습
rfr = RandomForestRegressor()
rfr.fit(x_train, y_train)
# 예측
# 예측은 학습에 사용된 Data와 Test Data 모두 예측하고 평가함(※ 과적합 여부 판별)
import numpy as np
from sklearn.metrics import mean_absolute_error, r2_score
y_pred_train = rfr.predict(x_train)
y_pred_test = rfr.predict(x_test)
mse_train = mean_absolute_error(y_train, y_pred_train)
print('mse_train(mse): ', mse_train)
rmse_train = (np.sqrt(mse_train))
print('rmse_train(rmse): ', rmse_train)
r2_train = r2_score(y_train, y_pred_train)
print('rmse_train(r2): ', r2_train)
print('')
mse_test = mean_absolute_error(y_test, y_pred_test)
print('mse_test(mse): ', mse_test)
rmse_test = (np.sqrt(mse_test))
print('rmse_test(rmse): ', rmse_test)
r2_test = r2_score(y_test, y_pred_test)
print('rmse_test(r2): ', r2_test)
이후는,, 나중에 복습하자