from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
iris = load_iris()
dt_clf = DecisionTreeClassifier()
train_data = iris.data
train_label = iris.target
# 학습 fit
dt_clf.fit(train_data, train_label)
# 학습 데이터 셋으로 예측 수행
pred = dt_clf.predict(train_data)
print('예측 정확도:',accuracy_score(train_label,pred))
# 예측 정확도 1.0 : 100% => 잘못된 결과 => train_data 학습 후 예측도 동일 데이터# 좋은 모델, 좋은 실력은 학습, 테스트 내용이 달라도 결과가 거의 동일해야 함# 예측 정확도: 1.0
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
dt_clf = DecisionTreeClassifier( )
iris_data = load_iris()
# x feature, y label# 학습, 테스트 분리 함수 train_test_split(featureset, target, 학7:테3, 시드번호)
X_train, X_test,y_train, y_test= train_test_split(iris_data.data, iris_data.target,
test_size=0.3, random_state=121)
kfold = KFold(n_splits=3)
# kfold.split(X)는 폴드 세트를 3번 반복할 때마다 달라지는 학습/테스트 용 데이터 로우 인덱스 번호 반환.
n_iter =0for train_index, test_index in kfold.split(iris_df):
n_iter += 1
label_train= iris_df['label'].iloc[train_index]
label_test= iris_df['label'].iloc[test_index]
print('## 교차 검증: {0}'.format(n_iter))
print('학습 레이블 데이터 분포:\n', label_train.value_counts())
print('검증 레이블 데이터 분포:\n', label_test.value_counts())
## 교차 검증: 1# 학습 레이블 데이터 분포:# 2 50# 1 50# Name: label, dtype: int64# 검증 레이블 데이터 분포:# 0 50# Name: label, dtype: int64# ## 교차 검증: 2# 학습 레이블 데이터 분포:# 2 50# 0 50# Name: label, dtype: int64# 검증 레이블 데이터 분포:# 1 50# Name: label, dtype: int64## 교차 검증: 3# 학습 레이블 데이터 분포:# 1 50# 0 50# Name: label, dtype: int64# 검증 레이블 데이터 분포:# 2 50# Name: label, dtype: int64
from sklearn.model_selection import StratifiedKFold
skf = StratifiedKFold(n_splits=3) # 쪼게주는 함수
n_iter=0# 유의점 : split할때 y값이 들어가야함 label값for train_index, test_index in skf.split(iris_df, iris_df['label']):
n_iter += 1
label_train= iris_df['label'].iloc[train_index]
label_test= iris_df['label'].iloc[test_index]
print('## 교차 검증: {0}'.format(n_iter))
print('학습 레이블 데이터 분포:\n', label_train.value_counts())
print('검증 레이블 데이터 분포:\n', label_test.value_counts())
## 교차 검증: 1
학습 레이블 데이터 분포:
234133033
Name: label, dtype: int64
검증 레이블 데이터 분포:
117017216
Name: label, dtype: int64
## 교차 검증: 2
학습 레이블 데이터 분포:
134233033
Name: label, dtype: int64
검증 레이블 데이터 분포:
217017116
Name: label, dtype: int64
## 교차 검증: 3
학습 레이블 데이터 분포:
034233133
Name: label, dtype: int64
검증 레이블 데이터 분포:
217117016
Name: label, dtype: int64
dt_clf = DecisionTreeClassifier(random_state=156)
skfold = StratifiedKFold(n_splits=3)
n_iter=0
cv_accuracy=[]
# StratifiedKFold의 split( ) 호출시 반드시 레이블 데이터 셋도 추가 입력 필요 for train_index, test_index in skfold.split(features, label):
# split( )으로 반환된 인덱스를 이용하여 학습용, 검증용 테스트 데이터 추출
X_train, X_test = features[train_index], features[test_index]
y_train, y_test = label[train_index], label[test_index]
#학습 및 예측
dt_clf.fit(X_train , y_train)
pred = dt_clf.predict(X_test)
# 반복 시 마다 정확도 측정
n_iter += 1
accuracy = np.round(accuracy_score(y_test,pred), 4)
train_size = X_train.shape[0]
test_size = X_test.shape[0]
print('\n#{0} 교차 검증 정확도 :{1}, 학습 데이터 크기: {2}, 검증 데이터 크기: {3}'
.format(n_iter, accuracy, train_size, test_size))
print('#{0} 검증 세트 인덱스:{1}'.format(n_iter,test_index))
cv_accuracy.append(accuracy)
# 교차 검증별 정확도 및 평균 정확도 계산 print('\n## 교차 검증별 정확도:', np.round(cv_accuracy, 4))
print('## 평균 검증 정확도:', np.mean(cv_accuracy))
#1 교차 검증 정확도 :0.98, 학습 데이터 크기: 100, 검증 데이터 크기: 50#1 검증 세트 인덱스:[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 5051525354555657585960616263646566100101102103104105106107108109110111112113114115]
#2 교차 검증 정확도 :0.94, 학습 데이터 크기: 100, 검증 데이터 크기: 50#2 검증 세트 인덱스:[ 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 67686970717273747576777879808182116117118119120121122123124125126127128129130131132]
#3 교차 검증 정확도 :0.98, 학습 데이터 크기: 100, 검증 데이터 크기: 50#3 검증 세트 인덱스:[ 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 83 84858687888990919293949596979899133134135136137138139140141142143144145146147148149]
## 교차 검증별 정확도: [0.98 0.94 0.98]## 평균 검증 정확도: 0.9666666666666667
print('GridSearchCV 최적 파라미터:', grid_dtree.best_params_)
print('GridSearchCV 최고 정확도: {0:.4f}'.format(grid_dtree.best_score_))
# refit=True로 설정된 GridSearchCV 객체가 fit()을 수행 시 학습이 완료된 Estimator를 내포하고 있으므로 predict()를 통해 예측도 가능.
pred = grid_dtree.predict(X_test)
print('테스트 데이터 세트 정확도: {0:.4f}'.format(accuracy_score(y_test,pred)))
# GridSearchCV 최적 파라미터: {'max_depth': 3, 'min_samples_split': 2}# GridSearchCV 최고 정확도: 0.9750# 테스트 데이터 세트 정확도: 0.9667
# GridSearchCV의 refit으로 이미 학습이 된 estimator 반환
estimator = grid_dtree.best_estimator_ # # GridSearchCV의 best_estimator_는 이미 최적 하이퍼 파라미터로 학습이 됨
pred = estimator.predict(X_test)
print('테스트 데이터 세트 정확도: {0:.4f}'.format(accuracy_score(y_test,pred)))
# 테스트 데이터 세트 정확도: 0.9667
피처feature는 데이터 세트의 일반 속성(attribute) 머신러닝은 2차원이상의 다차원 데이터에서도 많이 사용되므로 넓은, 범용의 타겟값을 제외한 나머지 속성을 모두 피처로 지칭
target(value), decision(value) - 지도학습시 학습위한 정답데이터 label, class은 지도학습 중 분류의 경우 결정 값을 레이블 또는 클래스로 지칭
분류(classfication)는 다양한 피처와 결정값, 레이블을 모델로 학습한뒤, 별도의 테스트 데이터 세트에서 미지의 레이블 예측 // 학습데이터 세트 & 테스트 데이터세트(성능평가용)
1) 데이터 세트분리 - 학습, 테스트 데이터 분리
2) 모델학습 - 학습 데이터 기반 학습
3) 예측수행 - 학습된 모델을 이용해 테스트 데이터의 분류(붓꽃 종류) 예측 4) 평가 - 예측된 결과값, 테스트 데이터의 실제 결과값 비교해 평가
# 사이킷런 버전 확인import sklearn
print(sklearn.__version__)
# 0.23.2
** 붓꽃 예측을 위한 사이킷런 필요 모듈 로딩 **
from sklearn.datasets import load_iris # 내장 데이터 셋 불러오기from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split # 테스트데이터 분리 함수
데이터 세트를 로딩
import pandas as pd
# 붓꽃 데이터 세트를 로딩합니다.
iris = load_iris()
# iris.data는 Iris 데이터 세트에서 피처(feature)만으로 된 데이터를 numpy로 가지고 있습니다.
iris_data = iris.data
# iris.target은 붓꽃 데이터 세트에서 레이블(결정 값) 데이터를 numpy로 가지고 있습니다.
iris_label = iris.target
print('iris target값:', iris_label)
print('iris target명:', iris.target_names)
# 붓꽃 데이터 세트를 자세히 보기 위해 DataFrame으로 변환합니다.
iris_df = pd.DataFrame(data=iris_data, columns=iris.feature_names)
iris_df['label'] = iris.target
iris_df.head(3)
iris target값: [000000000000000000000000000000000000000000000000001111111111111111111111111111111111111111111111111122222222222222222222222222222222222222222222222222]
iris target명: ['setosa''versicolor''virginica']
sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) label
05.13.51.40.2014.93.01.40.2024.73.21.30.20
** 학습 데이터와 테스트 데이터 세트로 분리 **
X_train, X_test, y_train, y_test = train_test_split(iris_data, iris_label, # X 피처, Y 타겟 test, train분리
test_size=0.2, random_state=11)
** 학습 데이터 세트로 학습(Train) 수행 **
# DecisionTreeClassifier 객체 생성
dt_clf = DecisionTreeClassifier(random_state=11)
# 학습 수행
dt_clf.fit(X_train, y_train)
# DecisionTreeClassifier(random_state=11)
** 테스트 데이터 세트로 예측(Predict) 수행 ** 별도의 데이터로 수행
# 학습이 완료된 DecisionTreeClassifier 객체에서 테스트 데이터 세트로 예측 수행.
pred = dt_clf.predict(X_test)
DataFrameGroupBy객체에 Aggregation함수를 호출하여 Group by 수행.
titanic_groupby = titanic_df.groupby('Pclass').count() # 인덱스명은 gb 된 pclass로 됨
titanic_groupby
PassengerId Survived Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
Pclass
1216216216216186216216216216176214218418418418417318418418418416184349149149149135549149149149112491
print(type(titanic_groupby))
print(titanic_groupby.shape) # 원래는 col이 12개인데 pclass가 index가 되면서 col이 11개가 됨print(titanic_groupby.index) # index는 name 이 pclass# <class 'pandas.core.frame.DataFrame'># (3, 11)# Int64Index([1, 2, 3], dtype='int64', name='Pclass')
titanic_groupby = titanic_df.groupby(by='Pclass')[['PassengerId', 'Survived']].count() # 또 특정 col 만 모으기 가능 브레이킷
titanic_groupby
PassengerId Survived
Pclass
121621621841843491491
titanic_df[['Pclass','PassengerId', 'Survived']].groupby('Pclass').count()
# 순서 상관없음 // col 먼저 따지면 메모리 최소화하기도 // 기존이 된 pclass는 무조건 넣어줘야함
PassengerId Survived
Pclass
121621621841843491491
agg_format={'Age':'max', 'SibSp':'sum', 'Fare':'mean'} # 각컬럼에 각기 다른 함수를 부여하고 싶다면 dict으로 key 부여
titanic_df.groupby('Pclass').agg(agg_format)
Age SibSp Fare
Pclass
180.09084.154687270.07420.662183374.030213.675550
Missing 데이터 처리하기
DataFrame의 isna( ) 메소드는 모든 컬럼값들이 NaN인지 True/False값을 반환함(NaN이면 True)
titanic_df.isna().head(3) # 모든 COL에 T/F 출력
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
0FalseFalseFalseFalseFalseFalseFalseFalseFalseFalseTrueFalse1FalseFalseFalseFalseFalseFalseFalseFalseFalseFalseFalseFalse2FalseFalseFalseFalseFalseFalseFalseFalseFalseFalseTrueFalse
아래와 같이 isna( ) 반환 결과에 sum( )을 호출하여 컬럼별로 NaN 건수를 구할 수 있습니다.
titanic_df.isna( ).sum( ) # NULL의 개수를 계산 VS COUNT와 반대
PassengerId 0
Survived 0
Pclass 0
Name 0
Sex 0
Age 177
SibSp 0
Parch 0
Ticket 0
Fare 0
Cabin 687
Embarked 2
dtype: int64
** fillna( ) 로 Missing 데이터를 인자로 대체하기 **
titanic_df['Cabin'] = titanic_df['Cabin'].fillna('C000') #NULL 이면 COOO으로 채워주줘
titanic_df.head(3)
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
0103 Braund, Mr.... male 22.010 A/5211717.2500 C000 S
1211 Cumings, Mr... female 38.010 PC 1759971.2833 C85 C
2313 Heikkinen, ... female 26.000 STON/O2. 31... 7.9250 C000 S
titanic_df['Age'] = titanic_df['Age'].fillna(titanic_df['Age'].mean())
titanic_df['Embarked'] = titanic_df['Embarked'].fillna('S')
titanic_df.isna().sum()
PassengerId 0
Survived 0
Pclass 0
Name 0
Sex 0
Age 0
SibSp 0
Parch 0
Ticket 0
Fare 0
Cabin 0
Embarked 0
dtype: int64
apply lambda // 함수 식으로 데이터 가공
파이썬 lambda 식 기본 // apply 함수에 lambda 결합, df, series에 레코드별 데이터 가공 기능,
보통은 일괄 데이터 가공이 속도면에서 빠르지만, 복잡한데이터 가공시 행별 apply lambda 이용
lambda x(입력 인자) : x**2(입력인자를 기반으로한 계산식이며 호출 시 계산 결과가 반환됨)
titanic_df = pd.read_csv('titanic_train.csv')
print('titanic 변수 type:',type(titanic_df))
# titanic 변수 type: <class 'pandas.core.frame.DataFrame'>
head() DataFrame의 맨 앞 일부 데이터만 추출
titanic_df.head(5)
# col, row 모든 값이 ndarray 2차원이니깐 // index는 차원에 포함 안됨
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
0103 Braund, Mr. Owen Harris male 22.010 A/5211717.2500 NaN S
1211 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38.010 PC 1759971.2833 C85 C
2313 Heikkinen, Miss. Laina female 26.000 STON/O2. 31012827.9250 NaN S
3411 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.01011380353.1000 C123 S
4503 Allen, Mr. William Henry male 35.0003734508.0500 NaN S
** DataFrame의 생성 **
dic1 = {'Name': ['Chulmin', 'Eunkyung','Jinwoong','Soobeom'],
'Year': [2011, 2016, 2015, 2015],
'Gender': ['Male', 'Female', 'Male', 'Male']
}
# 딕셔너리를 DataFrame으로 변환 // key 값이 col 나머지가 value로들어감
data_df = pd.DataFrame(dic1)
print(data_df)
print("#"*30)
# 새로운 컬럼명을 추가
data_df = pd.DataFrame(dic1, columns=["Name", "Year", "Gender", "Age"])
print(data_df)
print("#"*30)
# 인덱스를 새로운 값으로 할당.
data_df = pd.DataFrame(dic1, index=['one','two','three','four'])
# index 마음 대로 가능 //보통은 arange형인데print(data_df)
print("#"*30)
Name Year Gender
0 Chulmin 2011 Male
1 Eunkyung 2016 Female
2 Jinwoong 2015 Male
3 Soobeom 2015 Male
##############################
Name Year Gender Age
0 Chulmin 2011 Male NaN
1 Eunkyung 2016 Female NaN
2 Jinwoong 2015 Male NaN
3 Soobeom 2015 Male NaN
##############################
Name Year Gender
one Chulmin 2011 Male
two Eunkyung 2016 Female
three Jinwoong 2015 Male
four Soobeom 2015 Male
##############################
info() DataFrame내의 컬럼명, 데이터 타입, Null건수, 데이터 건수 정보를 제공합니다.
titanic_df.info()
# angeIndex: 891 entries, 0 to 890# Data columns (total 12 columns):# nonnull은 데이터가 존재한다. 차수만큼 없다. // object 는 string, 데이터 형 // 메모리 사용량 을 보여줌
<class 'pandas.core.frame.DataFrame'>
RangeIndex:891 entries, 0 to 890
Data columns (total 12 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 PassengerId 891 non-null int64
1 Survived 891 non-null int64
2 Pclass 891 non-null int64
3 Name 891 non-null object4 Sex 891 non-null object5 Age 714 non-null float64
6 SibSp 891 non-null int64
7 Parch 891 non-null int64
8 Ticket 891 non-null object9 Fare 891 non-null float64
10 Cabin 204 non-null object11 Embarked 889 non-null object
dtypes: float64(2), int64(5), object(5)
memory usage: 83.7+ KB
describe() 데이터값들의 평균,표준편차,4분위 분포도를 제공합니다. 숫자형 컬럼들에 대해서 해당 정보를 제공합니다.
titanic_df.describe()
# PassengerId Survived Pclass 정도는 소수점이 의미가 없음, 고유값이라서, null값은 빠진 평균값이다.
PassengerId Survived Pclass Age SibSp Parch Fare
count 891.000000891.000000891.000000714.000000891.000000891.000000891.000000
mean 446.0000000.3838382.30864229.6991180.5230080.38159432.204208
std 257.3538420.4865920.83607114.5264971.1027430.80605749.693429min1.0000000.0000001.0000000.4200000.0000000.0000000.00000025% 223.5000000.0000002.00000020.1250000.0000000.0000007.91040050% 446.0000000.0000003.00000028.0000000.0000000.00000014.45420075% 668.5000001.0000003.00000038.0000001.0000000.00000031.000000max891.0000001.0000003.00000080.0000008.0000006.000000512.329200
value_counts() 동일한 개별 데이터 값이 몇건이 있는지 정보를 제공합니다. 즉 개별 데이터값의 분포도를 제공함
주의할 점은 value_counts()는 Series객체에서만 호출 될 수 있으므로 반드시 DataFrame을 단일 컬럼으로 입력하여 Series로 변환한 뒤 호출해야 함.
sort_values()by=정렬컬럼, ascending=True 또는 False로 오름차순/내림차순으로 정렬
titanic_df.sort_values(by='Pclass', ascending=True)
titanic_df[['Name','Age']].sort_values(by='Age') # 특정값, age로 정렬
titanic_df[['Name','Age','Pclass']].sort_values(by=['Pclass','Age']) # 여러개의 칼럼 정렬 list로
Name Age Pclass
305 Allison, Master. Hudson Trevor 0.921297 Allison, Miss. Helen Loraine 2.001445 Dodge, Master. Washington 4.001802 Carter, Master. William Thornton II 11.001435 Carter, Miss. Lucile Polk 14.001
... ... ... ...
859 Razi, Mr. Raihed NaN 3863 Sage, Miss. Dorothy Edith "Dolly" NaN 3868 van Melkebeke, Mr. Philemon NaN 3878 Laleff, Mr. Kristo NaN 3888 Johnston, Miss. Catherine Helen "Carrie" NaN 3891 rows × 3 columns
새로운 컬럼에 값을 할당하려면 DataFrame [ ] 내에 새로운 컬럼명을 입력하고 값을 할당해주기만 하면 됨
titanic_df['Age_0']=0# 추가
titanic_df.head(3)
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked Age_0
0103 Braund, Mr. Owen Harris male 22.010 A/5211717.2500 NaN S 01211 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38.010 PC 1759971.2833 C85 C 02313 Heikkinen, Miss. Laina female 26.000 STON/O2. 31012827.9250 NaN S 0
titanic_df['Age_by_10'] = titanic_df['Age']*10
titanic_df['Family_No'] = titanic_df['SibSp'] + titanic_df['Parch']+1# 기존 컬럼을 통해 새로 생성
titanic_df.head(3)
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked Age_0 Age_by_10 Family_No
0103 Braund, Mr. Owen Harris male 22.010 A/5211717.2500 NaN S 0220.021211 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38.010 PC 1759971.2833 C85 C 0380.022313 Heikkinen, Miss. Laina female 26.000 STON/O2. 31012827.9250 NaN S 0260.01
기존 컬럼에 값을 업데이트 하려면 해당 컬럼에 업데이트값을 그대로 지정하면 됨
titanic_df['Age_by_10'] = titanic_df['Age_by_10'] + 100
titanic_df.head(3)
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked Age_0 Age_by_10 Family_No
0103 Braund, Mr. Owen Harris male 22.010 A/5211717.2500 NaN S 0320.021211 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38.010 PC 1759971.2833 C85 C 0480.022313 Heikkinen, Miss. Laina female 26.000 STON/O2. 31012827.9250 NaN S 0360.01
DataFrame 데이터 삭제
** axis에 따른 삭제**
titanic_drop_df = titanic_df.drop('Age_0', axis=1 )
titanic_drop_df.head(3)
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked Age_by_10 Family_No
0103 Braund, Mr. Owen Harris male 22.010 A/5211717.2500 NaN S 320.021211 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38.010 PC 1759971.2833 C85 C 480.022313 Heikkinen, Miss. Laina female 26.000 STON/O2. 31012827.9250 NaN S 360.01
drop( )메소드의 inplace인자의 기본값은 False 임
이 경우 drop( )호출을 한 DataFrame은 아무런 영향이 없으며
drop( )호출의 결과가 해당 컬럼이 drop 된 DataFrame을 반환함
titanic_df.head(3)
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked Age_0 Age_by_10 Family_No
0103 Braund, Mr. Owen Harris male 22.010 A/5211717.2500 NaN S 0320.021211 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38.010 PC 1759971.2833 C85 C 0480.022313 Heikkinen, Miss. Laina female 26.000 STON/O2. 31012827.9250 NaN S 0360.01
여러개의 컬럼들의 삭제는 drop의 인자로 삭제 컬럼들을 리스트로 입력함
inplace=True 일 경우 호출을 한 DataFrame에 drop이 반영됨
이 때 반환값은 None임
drop_result = titanic_df.drop(['Age_0', 'Age_by_10', 'Family_No'], axis=1, inplace=True)
print(' inplace=True 로 drop 후 반환된 값:',drop_result)
titanic_df.head(3)
# inplace=True 로 drop 후 반환된 값: None
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
0103 Braund, Mr. Owen Harris male 22.010 A/5211717.2500 NaN S
1211 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38.010 PC 1759971.2833 C85 C
2313 Heikkinen, Miss. Laina female 26.000 STON/O2. 31012827.9250 NaN S
axis=0 일 경우 drop()은 row 방향으로 데이터를 삭제함
titanic_df = pd.read_csv('titanic_train.csv')
pd.set_option('display.width', 1000)
pd.set_option('display.max_colwidth', 15)
print('#### before axis 0 drop ####')
print(titanic_df.head(6))
titanic_df.drop([0,1,2], axis=0, inplace=True)
print('#### after axis 0 drop ####')
print(titanic_df.head(3))
#### before axis 0 drop ####
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
0103 Braund, Mr.... male 22.010 A/5211717.2500 NaN S
1211 Cumings, Mr... female 38.010 PC 1759971.2833 C85 C
2313 Heikkinen, ... female 26.000 STON/O2. 31... 7.9250 NaN S
3411 Futrelle, M... female 35.01011380353.1000 C123 S
4503 Allen, Mr. ... male 35.0003734508.0500 NaN S
5603 Moran, Mr. ... male NaN 003308778.4583 NaN Q
#### after axis 0 drop ####
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
3411 Futrelle, M... female 35.01011380353.1000 C123 S
4503 Allen, Mr. ... male 35.0003734508.0500 NaN S
5603 Moran, Mr. ... male NaN 003308778.4583 NaN Q
Index 객체
# 원본 파일 재 로딩
titanic_df = pd.read_csv('titanic_train.csv')
# Index 객체 추출
indexes = titanic_df.index
print(indexes)
# Index 객체를 실제 값 arrray로 변환 print('Index 객체 array값:\n',indexes.values)
RangeIndex(start=0, stop=891, step=1)
Index 객체 array값:
[ 0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890]
indexes[0] = 5
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-29-2fe1c3d18d1a> in <module>
----> 1 indexes[0] = 5
~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in __setitem__(self, key, value)
40794080def__setitem__(self, key, value):
-> 4081raise TypeError("Index does not support mutable operations")
40824083def__getitem__(self, key):
TypeError: Index does not support mutable operations
Series 객체는 Index 객체를 포함하지만 Series 객체에 연산 함수를 적용할 때 Index는 연산에서 제외됨
print('Fair Series max 값:', series_fair.max())
print('Fair Series sum 값:', series_fair.sum())
print('sum() Fair Series:', sum(series_fair))
print('Fair Series + 3:\n',(series_fair + 3).head(3) )
# index 로 의미있는값이 나오는 경우가 있음, 그럼 인덱스를 컬럼으로 만들수 없을까? reset index# Fair Series max 값: 512.3292# Fair Series sum 값: 28693.9493# sum() Fair Series: 28693.949299999967# Fair Series + 3:# 0 10.2500# 1 74.2833# 2 10.9250# Name: Fare, dtype: float64
DataFrame 및 Series에 reset_index( ) 메서드를 수행하면 새롭게 인덱스를 연속 숫자 형으로 할당하며 기존 인덱스는 ‘index’라는 새로운 컬럼 명으로 추가함
titanic_reset_df = titanic_df.reset_index(inplace=False)
titanic_reset_df.head(3)
index PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
00103 Braund, Mr.... male 22.010 A/5211717.2500 NaN S
11211 Cumings, Mr... female 38.010 PC 1759971.2833 C85 C
22313 Heikkinen, ... female 26.000 STON/O2. 31... 7.9250 NaN S
titanic_reset_df.shape
# (891, 13)
print('### before reset_index ###')
value_counts = titanic_df['Pclass'].value_counts() # vc는 series => 고유 칼럼값이 필요한데 print(value_counts)
print('value_counts 객체 변수 타입:',type(value_counts))
new_value_counts = value_counts.reset_index(inplace=False)
print('### After reset_index ###')
print(new_value_counts)
print('new_value_counts 객체 변수 타입:',type(new_value_counts))
### before reset_index #### 3 491# 1 216# 2 184# Name: Pclass, dtype: int64# value_counts 객체 변수 타입: <class 'pandas.core.series.Series'>### After reset_index #### index Pclass# 0 3 491# 1 1 216# 2 2 184# new_value_counts 객체 변수 타입: <class 'pandas.core.frame.DataFrame'>
데이터 Selection 및 Filtering
DataFrame의 [ ] 연산자
넘파이에서 [ ] 연산자는 행의 위치, 열의 위치, 슬라이싱 범위 등을 지정해 데이터를 가져올 수 있음
하지만 DataFrame 바로 뒤에 있는 ‘[ ]’ 안에 들어갈 수 있는 것은 컬럼 명 문자(또는 컬럼 명의 리스트 객체), 또는 인덱스로 변환 가능한 표현식임
titanic_df = pd.read_csv('titanic_train.csv')
print('단일 컬럼 데이터 추출:\n', titanic_df[ 'Pclass' ].head(3))
print('\n여러 컬럼들의 데이터 추출:\n', titanic_df[ ['Survived', 'Pclass'] ].head(3))
print('[ ] 안에 숫자 index는 KeyError 오류 발생:\n', titanic_df[0]) # 숫자형 x 직접 칼럼명 넣어주는게 좋다
단일 컬럼 데이터 추출:
031123
Name: Pclass, dtype: int64
여러 컬럼들의 데이터 추출:
Survived Pclass
003111213
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
2894try:
-> 2895return self._engine.get_loc(casted_key)
2896except KeyError as err:
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 0
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
<ipython-input-35-16b79a4adf85> in <module>
2print('단일 컬럼 데이터 추출:\n', titanic_df[ 'Pclass' ].head(3))
3print('\n여러 컬럼들의 데이터 추출:\n', titanic_df[ ['Survived', 'Pclass'] ].head(3))
----> 4print('[ ] 안에 숫자 index는 KeyError 오류 발생:\n', titanic_df[0]) # 숫자형 x 직접 칼럼명 넣어주는게 좋다
~\anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
2900if self.columns.nlevels > 1:
2901return self._getitem_multilevel(key)
-> 2902 indexer = self.columns.get_loc(key)
2903if is_integer(indexer):
2904 indexer = [indexer]
~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
2895return self._engine.get_loc(casted_key)
2896except KeyError as err:
-> 2897raise KeyError(key) from err
28982899if tolerance isnotNone:
KeyError: 0
앞에서 DataFrame의 [ ] 내에 숫자 값을 입력할 경우 오류가 발생한다고 했는데, Pandas의 Index 형태로 변환가능한 표현식은 [ ] 내에 입력할 수 있음 가령 titanic_df의 처음 2개 데이터를 추출하고자 titanic_df [ 0:2 ] 와 같은 슬라이싱을 이용하였다면 정확히 원하는 결과를 반환해 줌
titanic_df[0:2] #허용은 해주지만 비추
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
0103 Braund, Mr.... male 22.010 A/5211717.2500 NaN S
1211 Cumings, Mr... female 38.010 PC 1759971.2833 C85 C
[ ] 내에 조건식을 입력하여 불린 인덱싱을 수행할 수 있음
(DataFrame 바로 뒤에 있는 []안에 들어갈 수 있는 것은 컬럼명과 불린인덱싱으로 범위를 좁혀서 코딩을 하는게 도움이 됨)
titanic_df[ titanic_df['Pclass'] == 3].head(3)
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
0103 Braund, Mr.... male 22.010 A/5211717.250 NaN S
2313 Heikkinen, ... female 26.000 STON/O2. 31... 7.925 NaN S
4503 Allen, Mr. ... male 35.0003734508.050 NaN S
* DataFrame iloc[ ] 연산자** 위치기반 인덱싱을 제공함
data_df.head()
Name Year Gender
one Chulmin 2011 Male
two Eunkyung 2016 Female
three Jinwoong 2015 Male
four Soobeom 2015 Male
data_df.iloc[0, 0]
# 'Chulmin'
# 아래 코드는 오류를 발생함
data_df.iloc[0, 'Name']
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~\anaconda3\lib\site-packages\pandas\core\indexing.py in _has_valid_tuple(self, key)
701try:
--> 702 self._validate_key(k, i)
703except ValueError as err:
~\anaconda3\lib\site-packages\pandas\core\indexing.py in _validate_key(self, key, axis)
1368else:
-> 1369raise ValueError(f"Can only index by location with a [{self._valid_types}]")
1370
ValueError: Can only index by location with a [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array]
The above exception was the direct cause of the following exception:
ValueError Traceback (most recent call last)
<ipython-input-60-ab5240d8ed9d> in <module>
1# 아래 코드는 오류를 발생합니다.
----> 2 data_df.iloc[0, 'Name']
~\anaconda3\lib\site-packages\pandas\core\indexing.py in __getitem__(self, key)
871# AttributeError for IntervalTree get_value872pass
--> 873return self._getitem_tuple(key)
874else:
875# we by definition only have the 0th axis
~\anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_tuple(self, tup)
1441def_getitem_tuple(self, tup: Tuple):1442
-> 1443 self._has_valid_tuple(tup)
1444try:
1445return self._getitem_lowerdim(tup)
~\anaconda3\lib\site-packages\pandas\core\indexing.py in _has_valid_tuple(self, key)
702 self._validate_key(k, i)
703except ValueError as err:
--> 704raise ValueError(
705"Location based indexing can only have "706f"[{self._valid_types}] types"
ValueError: Location based indexing can only have [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array] types
# 아래 코드는 오류를 발생합니다.
data_df.iloc['one', 0]
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~\anaconda3\lib\site-packages\pandas\core\indexing.py in _has_valid_tuple(self, key)
701try:
--> 702 self._validate_key(k, i)
703except ValueError as err:
~\anaconda3\lib\site-packages\pandas\core\indexing.py in _validate_key(self, key, axis)
1368else:
-> 1369raise ValueError(f"Can only index by location with a [{self._valid_types}]")
1370
ValueError: Can only index by location with a [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array]
The above exception was the direct cause of the following exception:
ValueError Traceback (most recent call last)
<ipython-input-61-0fe0a94ee06c> in <module>
1# 아래 코드는 오류를 발생합니다.
----> 2 data_df.iloc['one', 0]
~\anaconda3\lib\site-packages\pandas\core\indexing.py in __getitem__(self, key)
871# AttributeError for IntervalTree get_value872pass
--> 873return self._getitem_tuple(key)
874else:
875# we by definition only have the 0th axis
~\anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_tuple(self, tup)
1441def_getitem_tuple(self, tup: Tuple):1442
-> 1443 self._has_valid_tuple(tup)
1444try:
1445return self._getitem_lowerdim(tup)
~\anaconda3\lib\site-packages\pandas\core\indexing.py in _has_valid_tuple(self, key)
702 self._validate_key(k, i)
703except ValueError as err:
--> 704raise ValueError(
705"Location based indexing can only have "706f"[{self._valid_types}] types"
ValueError: Location based indexing can only have [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array] types
data_df_reset.head()
old_index Name Year Gender
1 one Chulmin 2011 Male
2 two Eunkyung 2016 Female
3 three Jinwoong 2015 Male
4 four Soobeom 2015 Male
data_df_reset.iloc[0, 1]
# 'Chulmin'
DataFrame loc[ ] 연산자 명칭기반 인덱싱을 제공함
data_df
Name Year Gender
one Chulmin 2011 Male
two Eunkyung 2016 Female
three Jinwoong 2015 Male
four Soobeom 2015 Male
# 아래 코드는 오류를 발생합니다. (단, 0없음)
data_df_reset.loc[0, 'Name']
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~\anaconda3\lib\site-packages\pandas\core\indexes\range.py in get_loc(self, key, method, tolerance)
354try:
--> 355return self._range.index(new_key)
356except ValueError as err:
ValueError: 0isnotinrange
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
<ipython-input-67-d3c58a57c329> in <module>
1# 아래 코드는 오류를 발생합니다. (단, 0없음)
----> 2 data_df_reset.loc[0, 'Name']
~\anaconda3\lib\site-packages\pandas\core\indexing.py in __getitem__(self, key)
871# AttributeError for IntervalTree get_value872pass
--> 873return self._getitem_tuple(key)
874else:
875# we by definition only have the 0th axis
~\anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_tuple(self, tup)
1042def_getitem_tuple(self, tup: Tuple):1043try:
-> 1044return self._getitem_lowerdim(tup)
1045except IndexingError:
1046pass
~\anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_lowerdim(self, tup)
784# We don't need to check for tuples here because those are785# caught by the _is_nested_tuple_indexer check above.
--> 786 section = self._getitem_axis(key, axis=i)
787788# We should never have a scalar section here, because
~\anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_axis(self, key, axis)
1108# fall thru to straight lookup1109 self._validate_key(key, axis)
-> 1110return self._get_label(key, axis=axis)
11111112def_get_slice_axis(self, slice_obj: slice, axis: int):
~\anaconda3\lib\site-packages\pandas\core\indexing.py in _get_label(self, label, axis)
1057def_get_label(self, label, axis: int):1058# GH#5667 this will fail if the label is not present in the axis.
-> 1059return self.obj.xs(label, axis=axis)
10601061def_handle_lowerdim_multi_index_axis0(self, tup: Tuple):
~\anaconda3\lib\site-packages\pandas\core\generic.py in xs(self, key, axis, level, drop_level)
3489 loc, new_index = self.index.get_loc_level(key, drop_level=drop_level)
3490else:
-> 3491 loc = self.index.get_loc(key)
34923493ifisinstance(loc, np.ndarray):
~\anaconda3\lib\site-packages\pandas\core\indexes\range.py in get_loc(self, key, method, tolerance)
355return self._range.index(new_key)
356except ValueError as err:
--> 357raise KeyError(key) from err
358raise KeyError(key)
359returnsuper().get_loc(key, method=method, tolerance=tolerance)
KeyError: 0
print('위치기반 iloc slicing\n', data_df.iloc[0:1, 0],'\n')
print('명칭기반 loc slicing\n', data_df.loc['one':'two', 'Name'])
# 위치기반 iloc slicing# one Chulmin# Name: Name, dtype: object # 명칭기반 loc slicing# one Chulmin# two Eunkyung# Name: Name, dtype: object
헷갈리는 위치기반, 명칭기반 인덱싱을 사용할 필요없이 조건식을 [ ] 안에 기입하여 간편하게 필터링을 수행.
titanic_df = pd.read_csv('titanic_train.csv')
titanic_boolean = titanic_df[titanic_df['Age'] > 60] # 불리언[ 불리언[] 연산자]print(type(titanic_boolean))
titanic_boolean
# <class 'pandas.core.frame.DataFrame'>
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
333402 Wheadon, Mr... male 66.000 C.A. 2457910.5000 NaN S
545501 Ostby, Mr. ... male 65.00111350961.9792 B30 C
969701 Goldschmidt... male 71.000 PC 1775434.6542 A5 C
11611703 Connors, Mr... male 70.5003703697.7500 NaN Q
17017101 Van der hoe... male 61.00011124033.5000 B19 S
25225301 Stead, Mr. ... male 62.00011351426.5500 C87 S
27527611 Andrews, Mi... female 63.0101350277.9583 D7 S
28028103 Duane, Mr. ... male 65.0003364397.7500 NaN Q
32632703 Nysveen, Mr... male 61.0003453646.2375 NaN S
43843901 Fortune, Mr... male 64.01419950263.0000 C23 C25 C27 S
45645701 Millet, Mr.... male 65.0001350926.5500 E38 S
48348413 Turkula, Mr... female 63.00041349.5875 NaN S
49349401 Artagaveyti... male 71.000 PC 1760949.5042 NaN C
54554601 Nicholson, ... male 64.00069326.0000 NaN S
55555601 Wright, Mr.... male 62.00011380726.5500 NaN S
57057112 Harris, Mr.... male 62.000 S.W./PP 75210.5000 NaN S
62562601 Sutton, Mr.... male 61.0003696332.3208 D50 S
63063111 Barkworth, ... male 80.0002704230.0000 A23 S
67267302 Mitchell, M... male 70.000 C.A. 2458010.5000 NaN S
74574601 Crosby, Cap... male 70.011 WE/P 573571.0000 B22 S
82983011 Stone, Mrs.... female 62.00011357280.0000 B28 NaN
85185203 Svensson, M... male 74.0003470607.7750 NaN S
titanic_df['Age'] > 60
var1 = titanic_df['Age'] > 60# []없이 하면 series 형태로 나옴 vs dataframeprint(type(var1))
# <class 'pandas.core.series.Series'>
titanic_df[titanic_df['Age'] > 60][['Name','Age']].head(3) #age > 60 인 data중에 name, age col로 3개 // SQL 느낌
Name Age
33 Wheadon, Mr... 66.054 Ostby, Mr. ... 65.096 Goldschmidt... 71.0
titanic_df[['Name','Age']][titanic_df['Age'] > 60].head(3) # 거꾸로해도 가능 : 유연성
Name Age
33 Wheadon, Mr... 66.054 Ostby, Mr. ... 65.096 Goldschmidt... 71.0
titanic_df.loc[titanic_df['Age'] > 60, ['Name','Age']].head(3) # loc 만으로 불린연산
Name Age
33 Wheadon, Mr... 66.054 Ostby, Mr. ... 65.096 Goldschmidt... 71.0
논리 연산자로 결합된 조건식도 불린 인덱싱으로 적용 가능함
titanic_df[ (titanic_df['Age'] > 60) & (titanic_df['Pclass']==1) & (titanic_df['Sex']=='female')] #논리연산자사용
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
27527611 Andrews, Mi... female 63.0101350277.9583 D7 S
82983011 Stone, Mrs.... female 62.00011357280.0000 B28 NaN
조건식은 변수로도 할당 가능함
복잡한 조건식은 변수로 할당하여 가득성을 향상 할 수 있음
cond1 = titanic_df['Age'] > 60
cond2 = titanic_df['Pclass']==1
cond3 = titanic_df['Sex']=='female'
titanic_df[ cond1 & cond2 & cond3] # 가독성을 위해 각각 - 효과적으로 사용
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
27527611 Andrews, Mi... female 63.0101350277.9583 D7 S
82983011 Stone, Mrs.... female 62.00011357280.0000 B28 NaN
array1 = np.arange(10)
array4 = array1.reshape(-1,4)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-23-a27748faa610> in <module>
1# -1 을 적용하여도 변환이 불가능한 형태로의 변환을 요구할 경우 오류 발생.2 array1 = np.arange(10)
----> 3 array4 = array1.reshape(-1,4)
ValueError: cannot reshape array of size 10 into shape (4)
# 반드시 -1 값은 1개의 인자만 입력해야 함. 모두가 불확정이 되어버림
array1.reshape(-1, -1)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-24-da23572df4ae> in <module>
1# 반드시 -1 값은 1개의 인자만 입력해야 함.
----> 2 array1.reshape(-1, -1)
ValueError: can only specify one unknown dimension
ndarray의 데이터 세트 선택하기 – 인덱싱(Indexing)
특정 위치의 단일값 추출
# 1에서 부터 9 까지의 1차원 ndarray 생성
array1 = np.arange(start=1, stop=10)
print('array1:',array1)
# index는 0 부터 시작하므로 array1[2]는 3번째 index 위치의 데이터 값을 의미
value = array1[2]
print('value:',value)
print(type(value))
# array1: [1 2 3 4 5 6 7 8 9]# value: 3# <class 'numpy.int32'>
print('맨 뒤의 값:',array1[-1], ', 맨 뒤에서 두번째 값:',array1[-2])
# 맨 뒤의 값: 9 , 맨 뒤에서 두번째 값: 8
array1d = np.arange(start=1, stop=10)
array2d = array1d.reshape(3,3)
print(array2d)
print('(row=0,col=0) index 가리키는 값:', array2d[0,0] )
print('(row=0,col=1) index 가리키는 값:', array2d[0,1] )
print('(row=1,col=0) index 가리키는 값:', array2d[1,0] )
print('(row=2,col=2) index 가리키는 값:', array2d[2,2] )
# [[1 2 3]# [4 5 6]# [7 8 9]]# (row=0,col=0) index 가리키는 값: 1# (row=0,col=1) index 가리키는 값: 2# (row=1,col=0) index 가리키는 값: 4# (row=2,col=2) index 가리키는 값: 9