import pandas as pd
import numpy as np
import seaborn as sns
titanic 데이터 불러오기
tt = sns.load_datset('titanic')
# 데이터 프레임
type(tt[['survived', 'pclass']])
# 시리즈
type(tt['survived'])
시리즈의 경우 빠른 연산이 가능
sum(tt['fare'])
head()
tt.head()
tail()
tt.tail()
# 실행 결과
survived pclass sex age sibsp parch fare embarked class who adult_male deck embark_town alive alone
0 0 3 male 22.0 1 0 7.2500 S Third man True NaN Southampton no False
1 1 1 female 38.0 1 0 71.2833 C First woman False C Cherbourg yes False
2 1 3 female 26.0 0 0 7.9250 S Third woman False NaN Southampton yes True
3 1 1 female 35.0 1 0 53.1000 S First woman False C Southampton yes False
4 0 3 male 35.0 0 0 8.0500 S Third man True NaN Southampton no True
tt.shape
# 실행 결과
survived pclass sex age sibsp parch fare embarked class who adult_male deck embark_town alive alone
886 0 2 male 27.0 0 0 13.00 S Second man True NaN Southampton no True
887 1 1 female 19.0 0 0 30.00 S First woman False B Southampton yes True
888 0 3 female NaN 1 2 23.45 S Third woman False NaN Southampton no False
889 1 1 male 26.0 0 0 30.00 C First man True C Cherbourg yes True
890 0 3 male 32.0 0 0 7.75 Q Third man True NaN Queenstown no True
tt.info()
# 실행 결과
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 891 entries, 0 to 890
Data columns (total 15 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 survived 891 non-null int64
1 pclass 891 non-null int64
2 sex 891 non-null object
3 age 714 non-null float64
4 sibsp 891 non-null int64
5 parch 891 non-null int64
6 fare 891 non-null float64
7 embarked 889 non-null object
8 class 891 non-null category
9 who 891 non-null object
10 adult_male 891 non-null bool
11 deck 203 non-null category
12 embark_town 889 non-null object
13 alive 891 non-null object
14 alone 891 non-null bool
dtypes: bool(2), category(2), float64(2), int64(4), object(5)
memory usage: 80.7+ KB
tt.describe() # 수치형 값만 나온다.
# 실행 결과
survived pclass age sibsp parch fare
count 891.000000 891.000000 714.000000 891.000000 891.000000 891.000000
mean 0.383838 2.308642 29.699118 0.523008 0.381594 32.204208
std 0.486592 0.836071 14.526497 1.102743 0.806057 49.693429
min 0.000000 1.000000 0.420000 0.000000 0.000000 0.000000
25% 0.000000 2.000000 20.125000 0.000000 0.000000 7.910400
50% 0.000000 3.000000 28.000000 0.000000 0.000000 14.454200
75% 1.000000 3.000000 38.000000 1.000000 0.000000 31.000000
max 1.000000 3.000000 80.000000 8.000000 6.000000 512.329200
tt.describe(include='all') # 모든 타입
# 실행 결과
survived pclass sex age sibsp parch fare embarked class who adult_male deck embark_town alive alone
count 891.000000 891.000000 891 714.000000 891.000000 891.000000 891.000000 889 891 891 891 203 889 891 891
unique NaN NaN 2 NaN NaN NaN NaN 3 3 3 2 7 3 2 2
top NaN NaN male NaN NaN NaN NaN S Third man True C Southampton no True
freq NaN NaN 577 NaN NaN NaN NaN 644 491 537 537 59 644 549 537
mean 0.383838 2.308642 NaN 29.699118 0.523008 0.381594 32.204208 NaN NaN NaN NaN NaN NaN NaN NaN
std 0.486592 0.836071 NaN 14.526497 1.102743 0.806057 49.693429 NaN NaN NaN NaN NaN NaN NaN NaN
min 0.000000 1.000000 NaN 0.420000 0.000000 0.000000 0.000000 NaN NaN NaN NaN NaN NaN NaN NaN
25% 0.000000 2.000000 NaN 20.125000 0.000000 0.000000 7.910400 NaN NaN NaN NaN NaN NaN NaN NaN
50% 0.000000 3.000000 NaN 28.000000 0.000000 0.000000 14.454200 NaN NaN NaN NaN NaN NaN NaN NaN
75% 1.000000 3.000000 NaN 38.000000 1.000000 0.000000 31.000000 NaN NaN NaN NaN NaN NaN NaN NaN
max 1.000000 3.000000 NaN 80.000000 8.000000 6.000000 512.329200 NaN NaN NaN NaN NaN NaN NaN NaN
tt.describe(include=['number']) # number 타입
tt.describe(include=['category', 'object']) # category, object 타입
list(tt.columns)
# 실행 결과
['survived',
'pclass',
'sex',
'age',
'sibsp',
'parch',
'fare',
'embarked',
'class',
'who',
'adult_male',
'deck',
'embark_town',
'alive',
'alone']
df = pd.DataFrame({'분반':['파문기', 'SQL','모델링', '데이터분석'],
'인워ㄴ':[100, 200, 300, 400]})
#변수 교체
df_1 = df_1.rename(columns = {'인워ㄴ':'인원'})
# 이 문법을 사용하면서 바로 원본을 수정하겠다 선언하는 게 inplce True
df_2.rename(columns = {'인워ㄴ':'인원'}, inplace=True)
bda_class=pd.DataFrame({'이름':['김길동','이길동','박길동','최길동','홍길동'],
'상점':[10,20,30,40,50],
'벌점':[1,2,3,5,8]})
# 변수처럼 생성
# 상점 - 벌점 = 최종상태 컬럼
bda_class['최종상태'] = bda_class['상점'] - bda_class['벌점']
# 넘파이의 where를 사용하여 파생변수 생성
# 최종상태에서 추가로 20점 이상이면 pass, 이하면 fail
bda_class['수료여부'] = np.where(bda_class['최종상태']>=20, 'pass', 'fail')
# 최종 실행 결과
이름 상점 벌점 최종상태 수료여부 new
0 김길동 10 1 9 fail 1
1 이길동 20 2 18 fail 2
2 박길동 30 3 27 pass 3
3 최길동 40 5 35 pass 4
4 홍길동 50 8 42 pass 5
bda_class['수료여부'].value_counts()
# 실행 결과
count
수료여부
pass 3
fail 2
dtype: int64
tt['embark_town'].value_counts()
# 실행 결과
count
embark_town
Southampton 644
Cherbourg 168
Queenstown 77
dtype: int64
# 시리즈 형태에서 인덱스 찾기
bda_class['이름'].loc[0]
# 데이터 프레임에서 인덱스 찾기
tt_1.loc[887]
# 시리즈 형태에서 인덱스 찾기
bda_class['이름'].iloc[0]
# 데이터 프레임에서 인덱스 찾기
tt.iloc[1]
tt.loc[5:80:3, ['fare', 's']]
tt.iloc[5:80:3, 1:5]
함수 | 설명 |
---|---|
query() | 조건에 맞는 데이터를 추출 |
df[[불린참값]] | 불린 참값을 기준으로 데이터 추출 |
df[] | 열 기준으로 데이터 추출 |
sort_values() | 데이터 정렬 |
groupby() | 그룹별로 데이터 집계 |
assign() | 새로운 변수를 추가할 때 사용하는 함수 |
merge() | 두 데이터프레임 병합 (SQL의 JOIN과 유사) |
concat() | 데이터프레임 병합 (행 또는 열 기준으로 연결) |
apply() | 함수나 전처리를 데이터프레임 전체에 적용 |
# 문자열 데이터
# 성별이 남자인 경우
tt.query('sex == "male"')
# 수치형 데이터
# 요금이 50 초과인 경우
tt.query('fare > 50')
# 다중 조건
# and, or 사용
# 요금이 50 초과이면서 나이가 20 미만인 경우
tt.query('fare > 50 & age < 20')
# 요금이 50 초과이거나 나이가 20 미만인 경우
tt.query('fare > 50 | age < 20')
# in 문법도 가능
# embar_town의 값이 Cherbourg, Southampton 중에 있는 하나인 경우
tt.query("embark_town in ['Cherbourg','Southampton']")
# 성별이 여성인 경우
tt[tt['sex']== 'female']
참고
tt[(tt['sex'] == 'female')&(tt['fare']>50)][['survived', 'fare']]