python_code

  • 데이터 읽기
엑셀에서 ; 있을 
df=pd.read_csv('/users/junghs/bank-additional-full.csv',sep=';')

use_cols
smartfarm = pd.read_csv(file_smartfarm, encoding = 'euc-kr', usecols=['호선', '역사명', '주소', '면적(㎡)', '재배작물'])
index설정
df = pd.read_csv("C:/adp/ISLR-python/Notebooks/Data/USArrests.csv",index_col='Unnamed: 0' )
데이터 불러올  문자열을 날짜로
train= pd.read_csv("C:/Users/landg/Downloads/archive (1)/train.csv",parse_dates =['date'])
경고 지우기
warnings.filterwarnings('ignore')
출력행 설정
pd.set_option('max_columns', 500)
pd.set_option('max_rows', 500)
  • import
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
from xgboost import XGBClassifier
from sklearn.metrics import plot_precision_recall_curve
from sklearn.metrics import plot_roc_curve
  • 그래프 그리기
sort_list = subway_rent.loc[subway_rent['상가유형'] == '공실'].groupby("호선").count().sort_values( "상가유형" , ascending = False)
sort_list = list(sort_list.index)
fig, ax = plt.subplots(figsize = (8,5))
c = sns.countplot(x = "호선", data = subway_rent.loc[subway_rent['상가유형'] == '공실'], ax = ax,order= sort_list,  palette = "pastel")

total = len(공실데이터)
for p in c.patches:
        percentage = '{:.1f}%'.format(100 * p.get_height()/total)
        x = p.get_x() + p.get_width() - 0.35
        y = p.get_height() + 1
        c.annotate(percentage, (x, y), ha = 'center')
       

    #plt.savefig('지하상가 노선별 공실율.png', bbox_inches = 'tight')


plt.show()
matplotlib  간단하게 feature importance를 barplot을  
seaborn은 분포를  

sns.histplot(x='age', data=df, hue='DEATH_EVENT', kde=True)
sns.jointplot(data=df, x = 'ejection_fraction', y="serum_creatinine", hue = 'DEATH_EVENT')
sns.boxplot(x='DEATH_EVENT', y='ejection_fraction', data=df, hue='smoking')

sns.swarmplot(x='DEATH_EVENT', y='platelets', hue='smoking', data=df)
#범주형 자료
sns.countplot( x= "NationalITy",hue = 'Class' ,data=df, hue_order= ["L", "M", "H"])
plt.xticks(rotation = 90)
plt.show()
#Logistic Regression 모델 계수로 상관성 파악하기
fig = plt.figure(figsize=(15,8))
plt.bar(X.columns,model_lr.coef_[0, :])
plt.xticks(rotation=90)
plt.show()

#XGBoost 모델로 특징의 중요도 확인하기

fig = plt.figure(figsize=(15,8))
plt.bar(X.columns,model_xgb.feature_importances_)
plt.xticks(rotation=90)
plt.show()


#히스토그램

#figsize=[15,8]
#xticks(fontsize=15)
#yticks(fontsize=15)
#plt.title('Histogram of df.age',fontsize=20)

df['age'].plot.hist(bins=range(10,101,10),figsize=[15,8]) #bins - 계급구간(10,20,30...100)
plt.xticks(fontsize=15)
plt.yticks(fontsize=15)
plt.title('Histogram of df.age',fontsize=20)
plt.show()

범주형 변수 그래프

marital=df['marital'].value_counts()
marital.plot.bar()
plt.show()
#plot함수 만들기
import seaborn as sns #matplot 에서 정제된 라이브러리
COLORS = sns.color_palette()
def plot_bar(df, xlabel, ylabel, title, color=COLORS[-1], figsize=(20, 10), rotation=45):
    plot = df.plot(kind='bar', color=color, figsize=figsize)
    plot.set_xlabel(xlabel, fontsize=11)
    plot.set_ylabel(ylabel, fontsize=11)
    plot.set_title(title, fontsize=13)
    plot.set_xticklabels(labels=df.index, rotation=rotation)
                   
plot_bar(rev_by_countries, 'Country', 'Revenue', 'Revenue by Country')

# DataFrame의 corr() 메소드와 Seaborn의 heatmap() 메소드를 이용하여 Pearson's correlation 시각화하기
fig = plt.figure(figsize=(12, 15))
sns.heatmap(df.corr())
# DataFrame의 corr() 메소드와 Seaborn의 heatmap() 메소드를 이용하여 Pearson's correlation 시각화하기

fig = plt.figure(figsize=(4, 10))
sns.heatmap(df.corr()[['blueWins']], annot=True)
  • 전처리
#이름으로 노가다

#subway_onoff["승차인원"] = subway_onoff["00시-01시 승차인원"]  
#for i in range(1,9):
#  subway_onoff["승차인원"] += subway_onoff["0" + str(i)+"시-0"+ str(i+1)+"시 승차인원"]  
#subway_onoff["승차인원"]  += subway_onoff['09시-10시 승차인원']
#for i in range(10,24):
 # subway_onoff["승차인원"] += subway_onoff[ str(i)+"시-"+ str(i+1)+"시 승차인원"] 
 #subway_onoff["하차인원"] = subway_onoff["00시-01시 하차인원"]  
 #for i in range(1,9):
 # subway_onoff["하차인원"] += subway_onoff["0" + str(i)+"시-0"+ str(i+1)+"시 하차인원"]  

#subway_onoff["하차인원"]  += subway_onoff['09시-10시 하차인원']

#for i in range(10,24):
# subway_onoff["하차인원"] += subway_onoff[ str(i)+"시-"+ str(i+1)+"시 하차인원"] 
# 전체 승차인원으로 나눠주기
#for i in range(0,9):
# subway_onoff["0" + str(i)+"시-0"+ str(i+1)+"시 승차인원"] /=subway_onoff["승차인원"] 
#subway_onoff['09시-10시 승차인원'] /= subway_onoff["승차인원"]     
#for i in range(10,24):
# subway_onoff[ str(i)+"시-"+ str(i+1)+"시 승차인원"] /=subway_onoff["승차인원"]   
# 전체 하차 인원으로 나눠주기 
#for i in range(0,9):
# subway_onoff["0" + str(i)+"시-0"+ str(i+1)+"시 하차인원"] /=subway_onoff["하차인원"]   
#subway_onoff['09시-10시 하차인원'] /= subway_onoff["하차인원"] 
#for i in range(10,24):
# subway_onoff[ str(i)+"시-"+ str(i+1)+"시 하차인원"] /=subway_onoff["하차인원"]     
#확인
#subway_onoff["승차총합"] = subway_onoff["00시-01시 승차인원"]
#for i in range(1,9):
# subway_onoff["승차총합"] += subway_onoff["0" + str(i)+"시-0"+ str(i+1)+"시 승차인원"]    
#subway_onoff["승차총합"]  += subway_onoff['09시-10시 승차인원']
#for i in range(10,24):
# subway_onoff["승차총합"] += subway_onoff[ str(i)+"시-"+ str(i+1)+"시 승차인원"] 
#subway_onoff["승차총합"]
#subway_onoff["하차총합"] = subway_onoff["00시-01시 하차인원"]  
#for i in range(1,9):
#  subway_onoff["하차총합"] += subway_onoff["0" + str(i)+"시-0"+ str(i+1)+"시 하차인원"]  

#subway_onoff["하차총합"]  += subway_onoff['09시-10시 하차인원']

##for i in range(10,24):
#  subway_onoff["하차총합"] += subway_onoff[ str(i)+"시-"+ str(i+1)+"시 하차인원"] 
#subway_onoff["하차총합"]

#subway_onoff.drop(['04시-05시 승차인원', '04시-05시 하차인원', '05시-06시 승차인원',
#       '05시-06시 하차인원', '06시-07시 승차인원', '06시-07시 하차인원', '07시-08시 승차인원',
#       '07시-08시 하차인원', '08시-09시 승차인원', '08시-09시 하차인원', '09시-10시 승차인원',
#       '09시-10시 하차인원', '10시-11시 승차인원', '10시-11시 하차인원', '11시-12시 승차인원',
#       '11시-12시 하차인원', '12시-13시 승차인원', '12시-13시 하차인원', '13시-14시 승차인원',
#       '13시-14시 하차인원', '14시-15시 승차인원', '14시-15시 하차인원', '15시-16시 승차인원',
#       '15시-16시 하차인원', '16시-17시 승차인원', '16시-17시 하차인원', '17시-18시 승차인원',
#       '17시-18시 하차인원', '18시-19시 승차인원', '18시-19시 하차인원', '19시-20시 승차인원',
#       '19시-20시 하차인원', '20시-21시 승차인원', '20시-21시 하차인원', '21시-22시 승차인원',
#       '21시-22시 하차인원', '22시-23시 승차인원', '22시-23시 하차인원', '23시-24시 승차인원',
#       '23시-24시 하차인원', '00시-01시 승차인원', '00시-01시 하차인원', '01시-02시 승차인원',
#       '01시-02시 하차인원', '02시-03시 승차인원', '02시-03시 하차인원', '03시-04시 승차인원',
#       '03시-04시 하차인원'],axis =1, inplace = True)
# 추출, 뽑을 때

Seoul_market = df_market2.loc[df_market2['소재지지번주소'].str.contains('서울')]
store_sm = store_sm[(store_sm['상권업종중분류명']=='가정/주방/인테리어')|(store_sm['상권업종중분류명']=='건강/미용식품')|(store_sm['상권업종중분류명']=='음/식료품소매')]
store_sm.head()
filter를 통해서 범주형 자료만 찾기.
col_cats = list(filter(lambda s: s.find('Class')>=0, df.columns))
df_cats = pd.get_dummies(df[col_cats], drop_first = True)
df_cats

df.rename(columns = {'old_nm' : 'new_nm'}, inplace = True)
#mapping
str = {"L" : -1, "M" : 0 , "H" : 1}
df['Class_value'] = df["Class"].map(str)

df['Class_value'] = df["Class"].map(dict(L=-1, M = 0, H =1))
# groupby
fill_mean_func = lambda g: g.fillna(g.mean())
subway_rent.groupby("영업업종").apply(fill_mean_func)
#rstrip
Nationwide_subway["역사명"].str.rstrip("역") 

#리스트 컴프리핸션
seoul_idx = [i for i in range(len(name['역사도로명주소'])) if not "서울" in str(name['역사도로명주소'][i])]
# index drop
name.drop(seoul_idx, inplace = True)
# 데이터 프레임에 데이터 추가
data_to_insert = {'역사명': '이수역', '역위도': 37.486682, '역경도':126.981845, "역사도로명주소" : "서울특별시 동작구 사당로 지하310 (사당동)"}
name = name.append(data_to_insert, ignore_index=True)
#replace
subway_all_location["역사명"] = subway_all_location["역사명"].str.replace(" " , "")
r'[1-3]'에서 r은 문자를 있는 그대로 판단하라는 것입니다.
예를들어 백슬래쉬는 escape를 해주는 기능이 있지만 r을 사용하면 백슬래쉬  자체로 판단하게 됩니다

^ 문자열의 시작 의미
보통 ^문자열은  처음과 일치함을 의미하지만, 문자 클래스[^문자열]에서는 not의 의미다. 클래스는 대괄호를 의미함.
* 0 이상 반복 (업어도 상관 없음)
#replace 괄호
Nationwide_subway["역사명"] = Nationwide_subway["역사명"].replace('\([^)]*\)',"",regex=True)
https://whatisthenext.tistory.com/116
#concat
pd.concat([a, b["일평균기대생산량"]], axis =1 )
def df_scaler(data, cols, scale):
    df_cp = data.copy()
    
    if scale == "minmax":
        X = df_cp.loc[:,cols]
        MinMaxScalers = MinMaxScaler()
        MinMaxScalers.fit(X)
        df_MinMaxScaler = MinMaxScalers.transform(X)
        df_cp.loc[:, cols] = df_MinMaxScaler
    elif scale == "standardscaler" :
        X = df_cp.loc[:,cols]
        StandardScalers = StandardScaler()
        StandardScalers.fit(X)
        df_StandardScalers = StandardScalers.transform(X)
        df_cp.loc[:, cols] = df_StandardScalers
    elif scale == "RobustScaler" :
        X = df_cp.loc[:,cols]
        RobustScalers = RobustScaler()
        RobustScalers.fit(X)
        df_RobustScaler = RobustScalers.transform(X)
        df_cp.loc[:, cols] = df_RobustScaler
    else:
        print("wrong")
    return df_cp
    
# 한글
def set_hangul(font_path = "C:/Windows/Fonts/malgun.TTF"):
    '''
    seaborn, matplotlib, pandas로 시각화 할 때 한글출력 설정
    # 필수 import 라이브러리)
    @ seaborn
    @ matplotlib.pyplot
    @ font_manager, rc
    
    # parameter)
    @ font_path : 사용할 폰트의 경로
    '''
    
    sns.set_theme(style="whitegrid") # seaborn 스타일 설정
    
    plt.rcParams['font.family'] = 'NanumGothic'
    sns.set(font='NanumGothic',
            rc={'axes.unicode_minus':False},
            style='darkgrid')
    
    # pandas plot 한글폰트
    font = font_manager.FontProperties(fname=font_path).get_name()
    rc('font', family=font)
    
set_hangul()
정규표현식
def clean_text(text):
    pattern = '([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)' 
    text = re.sub(pattern=pattern, repl='', string=text)
    print("E-mail제거 : " , text , "\n")
    pattern = '(http|ftp|https)://(?:[-\w.]|(?:%[\da-fA-F]{2}))+'
    text = re.sub(pattern=pattern, repl='', string=text)
    print("URL 제거 : ", text , "\n")
    pattern = '([ㄱ-ㅎㅏ-ㅣ]+)'  
    text = re.sub(pattern=pattern, repl='', string=text)
    print("한글 자음 모음 제거 : ", text , "\n")
    pattern = '<[^>]*>'        
    text = re.sub(pattern=pattern, repl='', string=text)
    print("태그 제거 : " , text , "\n")
    pattern = r'\([^)]*\)'
    text = re.sub(pattern=pattern, repl='', string=text)
    print("괄호와 괄호안 글자 제거 :  " , text , "\n")
    pattern = '[^\w\s]'   
    text = re.sub(pattern=pattern, repl='', string=text)
    print("특수기호 제거 : ", text , "\n" )
    text = text.strip()
    print("양 끝 공백 제거 : ", text , "\n" )
    text = " ".join(text.split())
    print("중간에 공백은 1개만 : ", text )
    return text   
    
text = '(abc_def) 좋은글! (이것도 지워조) http://1234.com 감사합니다. aaa@goggle.comㅋㅋ<H1>thank you</H1>'
clean_text(text)

## result 

E-mail제거 :  (abc_def) 좋은글! (이것도 지워조) http://1234.com 감사합니다. ㅋㅋ<H1>thank you</H1> 

URL 제거 :  (abc_def) 좋은글! (이것도 지워조)  감사합니다. ㅋㅋ<H1>thank you</H1> 

한글 자음 모음 제거 :  (abc_def) 좋은글! (이것도 지워조)  감사합니다. <H1>thank you</H1> 

태그 제거 :  (abc_def) 좋은글! (이것도 지워조)  감사합니다. thank you 

괄호와 괄호안 글자 제거 :    좋은글!   감사합니다. thank you 

특수기호 제거 :   좋은글   감사합니다 thank you 

  공백 제거 :  좋은글   감사합니다 thank you 

중간에 공백은 1개만 :  좋은글 감사합니다 thank you
# time 시간
subway_group['사용월'] = pd.to_datetime(subway_group['사용월'], format="%Y%m")
subway_group.insert(1,'년', subway_group['사용월'].dt.year)
# 문자 데이터프레임 
for i in range(5):
    exec(f"이수_{i}['역사명'][0] = '이수'")
#loc
subway_rent.loc[subway_rent['상가유형'] != '공실', '상가유형'] = 0 # 공실이 아니면 0
subway_rent.loc[subway_rent['상가유형'] == '공실', '상가유형'] = 1 # 공실이면 1
#group by
gb = df.groupby('Topic').mean()['Class_value'].sort_values() 
plt.barh(gb.index,gb) ##그래프 가로로 그려준다.


def most(x) :
  return x.value_counts().index[0]

#team_api_id별로 groupby하고 그 값에 평균 또는 가장 많이 나온 관측값roupby하고 그 값에 평균 또는 가장 많이 나온 관측값
team_map = df_team_att.groupby('team_api_id').aggregate(
    {
       'buildUpPlaySpeed': 'mean',
       'buildUpPlaySpeedClass': most
    }
)
#contain
Seoul_market1 = Seoul_market.loc[df_market2['취급품목'].str.contains('농')]
#home이라고 붙은거랑 away라고 붙은 것들에 대해서 index생성해서 map해주기
for team in ['home_', 'away_']:
  team_map.index.name = team + 'team_api_id'
  for col in team_map.columns:
    df[team + col] = df_match[team_map.index.name].map(team_map[col])
# 1. 가입여부에 따라 가입한 그룹과 가입하지 않은 그룹으로 나눈다.
#groupby('y')
grouped=df.groupby('y')
#get_group('yes') - y칼럼이 'yes'인 데이터프레임 추출 - 가입한 그룹만 추출
#get_group('no') - y칼럼이 'no'인 데이터프레임 추출 - 가입하지 않은 그룹만 추출
yes_group=grouped.get_group('yes')
no_group=grouped.get_group('no')
#2. 나뉜 데이터(yes_group,no_group)를 대출여부(loan)에 따라 나눈다.value_counts
yes=yes_group['loan'].value_counts()
#3. 가입한 그룹 중 대출이 있는 사람의 비중과, 가입하지 않은 그룹 중 대출이 있는 사람의 비중을 비교한다.
concat : 시리즈 혹은 데이터프레임 결합(default-행방향 결합)
pd.concat([yes,no],axis=1) 
#칼럼명이 모두 loanseries.name : 시리즈의 이름 설정
yes.name='y_yes’
#pd.pivot_table('데이터프레임 변수',values=집계 대상 칼럼, index=행 인덱스가 될 칼럼명, columns=열 인덱스가 될 칼럼명, aggfunc=sum)
pd.pivot_table(df,values='age',index='y',columns='job',aggfunc='mean')

#열의 고유값
df['education'].unique()
#열안에 종류가 뭔지.
for i in X_cat:
    print(df[i].value_counts())
#value_counts() - 열의 고유값 빈도
df['education'].value_counts()
#오름차순 정렬 age칼럼 
age=df['age'].sort_values()
#reset_index - 인덱스 재생성, 기존 인덱스를 데이터프레임의 열로 반환
age=age.reset_index()

#drop(axis=1) - 삭제(열 기준)
age=age.drop('index',axis=1)
drop  어디서부터 어디까지. 
df_match.drop(df_match.columns[-38:], axis =1, inplace = True)
a = sorted(lose, key=lambda x: lose[x], reverse=True)   #values를 기준으로 내림차순으로 정렬해서 key값만 리스트로 반환
a = dict(sorted(lose.items(), key=lambda x: x[1], reverse=True)) #values를 기준으로 내림차순으로 정렬해서 tuple 반환
list(a.keys()) #dict에서 key값만 반환
#apply
y = y.apply(lambda x: value_change(x))  
group by table 테이블
gb = subway_rent.groupby("영업업종" , as_index=False)["면적"].mean()
drop, apply, map, groupby
df_match['away_player_1'].dropna().apply(int).map(df_player_att.groupby('player_api_id')['overall_rating'].mean()).isna().sum()
#drop 한 줄 
(((df['duration'].sort_values()).reset_index()).drop('index',axis=1))
#데이터 구조확인
retail.info()
#데이터 통계량 요약
retail.describe()
cat.codes  통해 ages의  성분이  번째 구간에 속해있는지 정수 index처럼 표시되는 것을   있다.
train['Sex_clean'] = train['Sex'].astype('category').cat.codes
generator
for col in (s + str(idx) for s in ['home_player_', 'away_player_'] for idx in range(1, 12)):
  df[col + '_rating']= df_match[col].map(player_map)
pd.qcut 이산화 가능 범주형 가능
pd.qcut(train['Fare'], 4)
3범주로 나누기 
df['matchResult'] = df[['home_team_goal','away_team_goal']].aggregate(lambda x: 0 if  x[0] > x[1] else 1 if x[0] == x[1] else 2, axis =1)
train['Title'] = train['Name'].str.extract(' ([A-Za-z]+)\.',  expand= False)
expand가 true인 경우 출력을 하나의 column단위로 나타내고 false일 경우 label 단위로 출력한다.
name에서 대문자로 시작하여 이후에는 소문자가 나열되며 . 만나면 탐색을 멈춘다.

범주형 변수 변환
train['Title']=train['Title'].replace(['Lady','Jonkheer','Dona'],'Other')
#널값 몇개인지
retail.isnull().sum()
레이블 인코딩
from sklearn import preprocessing

categorical = ['workclass', 'marital.status', 'occupation', 'relationship', 'race', 'sex', 'native.country']
for feature in categorical:
        le =  preprocessing.LabelEncoder()
        X_train[feature] = le.fit_transform(X_train[feature])
        X_test[feature] = le.transform(X_test[feature]) #fit을 안쓰는 이유는 train데이터와 범주에 똑같은 기준을 적용하기 위해서이다. 
널아닌거 제거
1. retail = retail[pd.notnull(retail['CustomerID'])]
len(retail)

2.retail = retail[retail['Quantity'] > 0]
retail = retail[retail['UnitPrice'] > 0]
# 컬럼 조건 삭제
idx_67 = subway_rent[subway_rent["상가유형"] == "67일괄"].index
subway_rent.drop(idx_67 , inplace = True)
#결측값 평균으로

train["Age"].fillna(train.groupby("Title")["Age"].transform("median"), inplace=True)
dfX["age"].fillna(dfX["age"].mean(), inplace=True
기준별로 범주화하면서 새로운 컬럼 생성
train.loc[ train['Age'] <= 16, 'Age_clean'] = 0
loc는 컬럼 이름으로
iloc 컬럼 번호로 컬럼 번호로
스케일 조절하기
# 데이터 스케일 조정하기
from sklearn.preprocessing import StandardScaler, RobustScaler

std_scaler =  StandardScaler()
rob_scaler =  RobustScaler()

df['scaled_amount'] =  rob_scaler.fit_transform(df['Amount'].values.reshape(-1,1))
df['scaled_time'] =  rob_scaler.fit_transform(df['Time'].values.reshape(-1,1))

# 원 데이터에서 Time 컬럼과 Amount 컬럼 제외하기
df.drop(['Time', 'Amount'], axis = 1, inplace = True)
# 스케일 조정된 컬럼 추가하기
scaled_amount = df['scaled_amount']
scaled_time = df['scaled_time']

df.drop(['scaled_amount', 'scaled_time'], axis=1, inplace=True)
df.insert(0, 'scaled_amount', scaled_amount)
df.insert(1, 'scaled_time', scaled_time)

## 스케일 조정된 데이터 확인하기

kfold
k_fold = KFold(n_splits=10, shuffle = True, random_state=0)
display 사용하면 여러개를 한번에 
열에 종류가  있는지
train.columns

데이터  끼리의 차이
train.columns.difference(test.columns) # train과 test데이터 차이
# Train-set의 id는?
print("Min/Max of id in Train-set")
display( train['id'].agg(['min','max']) )

print('='* 80)
print(f'Size : {len(train)}')
데이터  열에서 고유한  뽑기
set(train['bus_route_id'])
train['bus_route_id'].value_counts() 같음
다른 데이터 셋의 열끼리 공통된 고유의행 뽑기
train_bus_route_id_set.intersection(test_bus_route_id_set)
다른 데이터  열에는 없는  뽑기
train_bus_route_id_set.difference(test_bus_route_id_set)
오직  데이터 셋에 있는 고유값의 행을 뽑고 싶을  
test[test['bus_route_id'].isin(only_test_bus_route)].head() 
# 현황이 지연인 데이터만 추출
rawdata = rawdata[rawdata.현황.isin(['지연'])]
#날짜 처리
# 날짜데이터 스트링 형태로 변환
incheon_delay_pass['날짜'] = incheon_delay_pass['날짜'].astype(str)

# 날짜데이터 데이터 타입을 데이트타입으로 변환
incheon_delay_pass['날짜'] = incheon_delay_pass.날짜.apply(lambda X: dt.datetime.strptime(X, '%Y%m%d'))

# 년도 컬럼 생성
incheon_delay_pass['년도'] = incheon_delay_pass.날짜.apply(lambda X: X.strftime('%Y'))

# 월(month),일(day), 주차(weekNumber), 요일(weekDay) 칼럼 생성하기
incheon_delay_pass['월'] = incheon_delay_pass.날짜.apply(lambda X: X.strftime('%m'))
incheon_delay_pass['일'] = incheon_delay_pass.날짜.apply(lambda X: X.strftime('%d'))
incheon_delay_pass['주차'] = incheon_delay_pass.날짜.apply(lambda X: X.strftime('%U'))
incheon_delay_pass['요일'] = incheon_delay_pass.날짜.apply(lambda X: X.strftime('%a'))
데이터 셋에 있는 컬럼들을 하나하나씩 뽑아라
[col for col in test.columns]
_ride가 포함된 것만 뽑아라 버스루트랑 날짜	
[col for col in test.columns if '_ride' in col] + ['bus_route_id','date']

결측치 컬럼별로 보기
for c, num in zip(df_match.columns, df_match.isna().sum()):
  print(c,num)
결측치 그래프
# Missing Values
msno.matrix(train)

행별로 결측값이 있는지 확인
로그변환
# log1p transformation을 적용해봐도 정규분포에 근사한 모양을 보이지 않는다.
sns.distplot( np.log1p( train[target_col] ) )

유니크
train.groupby('station_name')['station_code'].agg(['nunique'])
중복 없애기
df_sample = df_sample.drop_duplicates().reset_index(drop=True)
파생변수 생성 
df['group'] = ['A' if f else 'B' for f in list(df['target'] %2 ==0)]
데이터프레임 정렬
ratio_df.sort_values('ratio', ascending = False)
  • 수치형 입력 데이터를 전처리하고 입력 데이터 통합하기
array행렬에서 한열  뽑기
X_reduced_tsne[:,0] , X_reduced_tsne[:,1]
from sklearn.preprocessing import StandardScaler
#정규화,표준화 
#1 numeric과 category가 있을때
scaler = StandardScaler()
scaler.fit(X_num) #학습
X_scaled  = scaler.transform(X_num) #변환
X_scaled = pd.DataFrame(data=X_scaled, index = X_num.index, columns = X_num.columns)
X = pd.concat([X_scaled, X_cat],axis=1) # 옆으로!


X = df
scaler = StandardScaler()
X_scaled = StandardScaler().fit_transform(X)
X = pd.DataFrame(data=X_scaled, index=X.index, columns=X.columns)

  • 학습데이터 분리
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test =  train_test_split(  X, y,test_size = 0.3, random_state=1)
  • 모델 학습
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
# LogisticRegression 모델 생성/학습
model_lr = LogisticRegression(max_iter= 1000)
model_lr.fit(X_train, y_train)
pred =  model_lr.predict(X_test)
print(classification_report(y_test, pred))
from xgboost import XGBClassifier
from sklearn.metrics import classification_report
model_xgb = XGBClassifier()
model_xgb.fit(X_train, y_train)
pred = model_xgb.predict(X_test)
print(classification_report(y_test, pred))

  • feature importances
전체클릭  ctrl /
plt.bar(X.columns,model_xgb.feature_importances_)
plt.xticks(rotation = 90)
plt.show()

  • precision recall curve
from sklearn.metrics import plot_precision_recall_curve
fig = plt.figure()
ax = fig.gca()
plot_precision_recall_curve(model_lr, X_test, y_test, ax=ax)
plot_precision_recall_curve(model_xgb, X_test, y_test, ax=ax)

  • ROC curve
from sklearn.metrics import plot_roc_curve
fig = plt.figure()
ax = fig.gca()
plot_roc_curve(model_lr, X_test, y_test, ax=ax)
plot_roc_curve(model_xgb, X_test, y_test, ax=ax)



Comments