# pip install pandas
import pandas as pd
# tab 으로 구분된 파일은 read.table() 사용
# 첫 줄 header=T 디폴트
titanic_df = pd.read_csv('titanic_train.csv')
print('titanic 변수 type:',type(titanic_df))
titanic_df
# .head(원하는 갯수)
titanic_df.head()
# .shape()
titanic_df.shape
# 12개의 변수 891개의 데이터
# .info() - R에서의 str() 같은 역할
# 상세 정보조회 : 컬럼타입, Null Data 개수 등
# object : 거의 문자열, Age, Cabin 컬럼에 Null 값이 많이 있음
titanic_df.info()
# .describe()
# R의 summary() 같은 함수
# 숫자형의 분포만 보여줌 (object 타입의 칼럼은 제외)
# 데이터의 분포도는 중요 : 회귀분석에서 결정 값이 정규분포를 따르지 않는 다던가 이상치가 많으면 예측치가 저하됨
# 카테고리 칼럼(Survived 0,1 : Pclass 1,2,3)도 확인 가능(R의 Facter형)
titanic_df.describe()
# .value_counts() : Sereis의 유형별 건수 확인, R의 table()
# R에서의 table()과 같은 역할
# DataFrame[컬럼명] : Series 형태로 특정 칼럼 데이터 세트를 반환
value_counts = titanic_df['Pclass'].value_counts()
print(value_counts)
# type 확인
# 변수 하나만 가져오면 타입은 시리즈가 됨 ->시리즈는 R의 데이터테이블과 같음
titanic_pclass = titanic_df['Pclass']
print(type(titanic_pclass))
# Series - Index : value
titanic_pclass.head()
# 왼쪽 숫자를 인덱스라 함. key값이기 때문에 변하지 않음
# titanic_pclass.tail()
value_counts = titanic_df['Pclass'].value_counts()
print(type(value_counts)) # 시리즈가 리턴됨
print('-----------------------------')
print(value_counts) # 3 1 2 가 index
# pip install numpy
import numpy as np
# 1차원 컬림 1개 필요
col_name1 = ['col1']
list1 = [1, 2, 3]
array1 = np.array(list1)
print('array1 shape:', array1.shape )
df_list1 = pd.DataFrame(list1, columns=col_name1)
print('1차원 리스트로 만든 DataFrame:\n', df_list1)
df_array1 = pd.DataFrame(array1, columns=col_name1)
print('1차원 ndarray로 만든 DataFrame:\n', df_array1)
# 2차원: 2 x 3 / 3개의 컬럼명이 필요함.
col_name2=['col1', 'col2', 'col3']
# 2행x3열 형태의 리스트와 ndarray 생성 한 뒤 이를 DataFrame으로 변환.
list2 = [[1, 2, 3],
[11, 12, 13]]
array2 = np.array(list2)
print('array2 shape:', array2.shape )
print('-----------------------------')
df_list2 = pd.DataFrame(list2, columns=col_name2)
print('2차원 리스트로 만든 DataFrame:\n', df_list2)
print('-----------------------------')
df_array2 = pd.DataFrame(array2, columns=col_name2)
print('2차원 ndarray로 만든 DataFrame:\n', df_array2)
# dict 형은 Key는 컬럼명으로 매핑, Value는 리스트 형(또는 ndarray)
# dict = {'컬럼명' : [리스트/ndarray]}
dict = {'col1':[1, 11], 'col2':[2, 22], 'col3':[3, 33]}
df_dict = pd.DataFrame(dict)
print('딕셔너리로 만든 DataFrame:\n', df_dict)
# DataFrame 을 list, ndarray 로 변환 - values 속성
array3 = df_dict.values
print(type(array3))
print('-----------')
print(array3.shape)
print('-----------')
print(array3)
# DataFrame을 리스트로 변환 - tolist()
list3 = df_dict.values.tolist()
print(type(list3))
print(list3)
# DataFrame을 딕셔너리로 변환 - to_dict()
dict3 = df_dict.to_dict('list')
print(type(dict3))
print(dict3)
# 새로운 컬럼(Series) 추가, 초기화
titanic_df['Age_0']=0
titanic_df.head(3)
# 기존 컬럼 이용하여 새로운 컬럼 생성
titanic_df['Age_by_10'] = titanic_df['Age']*10
titanic_df['Family_No'] = titanic_df['SibSp'] + titanic_df['Parch'] + 1
# SibSp : 형제자매, Parch : 부모 자식, +1 은 '나'
titanic_df.head(3)
titanic_df['Age_by_10'] = titanic_df['Age_by_10'] + 100
titanic_df.head(3)
# 열 삭제
titanic_drop_df = titanic_df.drop('Age_0', axis=1)
titanic_drop_df.head(3)
# 원본데이터는 삭제되지 않았음 inplace = False
titanic_df.head(3)
# 원본 데이터도 삭제 inplace = True
# 여러 개 삭제 시 리스트 값
drop_result = titanic_df.drop(['Age_0', 'Age_by_10', 'Family_No'], axis=1, inplace=True)
print('inplace=True 로 drop 후 반환된 값:',drop_result) # 반환값 None
titanic_df.head(3)
print('#### before axis 0 drop ####')
print(titanic_df.head(5))
# 행 삭제
titanic_df.drop([0,1,2], axis=0, inplace=True)
print('#### after axis 0 drop ####')
print(titanic_df.head(5))
# 원본 파일 재 로딩
titanic_df = pd.read_csv('titanic_train.csv')
# Index 객체 추출
indexes = titanic_df.index
print(indexes)
print('--------------------------------------------------------------------------')
print(indexes.values)
# Index 객체를 실제 값 arrray로 변환
print(type(indexes.values))
print(indexes.values.shape)
# (891,) : 1차원
print(indexes[:5].values)
# 처음~5개까지 슬라이싱
print(indexes.values[:5])
indexes[:5]
print(indexes[6])
# 인덱스 값은 key 값이기때문에 변경 불가. 식별용으로만 사용
indexes[6] = 1
series_fair = titanic_df['Fare']
# max
print('Fair Series max 값:', series_fair.max())
# sum
print('Fair Series sum 값:', series_fair.sum())
# sum
print('sum() Fair Series:', sum(series_fair))
print('Fair Series + 3:\n',(series_fair + 3).head(3) )
# reset_index()
# index 새로 만들 때 사용, 연속된 index 아닐때 주로 사용
# 기존 index 삭제 시에는 drop=True 속성 사용
# (default)inplace=False / 원본 훼손하지 않기 위해 (inplace=True 속성을 넣고 실행하면 원본 훼손 됨)
titanic_reset_df = titanic_df.reset_index()
titanic_reset_df.head(3)
# value_counts 리셋 전
print('### before reset_index ###')
value_counts = titanic_df['Pclass'].value_counts()
print(value_counts)
print('-------------------------------------------------')
print('value_counts 객체 변수 타입:',type(value_counts))
# .reset_index 를 통해 value_counts 리셋 후
new_value_counts = value_counts.reset_index()
print('### After reset_index ###')
print(new_value_counts)
print('-------------------------------------------------')
print('new_value_counts 객체 변수 타입:',type(new_value_counts))
# 단일 컬럼 데이터 추출 (컬럼명이 아니고 숫자를 넣으면 오류남)
titanic_df['Pclass'].head(3)
# 여러 컬럼 데이터 추출
print(titanic_df[['Survived','Pclass']].head(3))
# 여러 행 추출
titanic_df[0:2]
# 열 조건에 맞는 데이터 추출
titanic_df[titanic_df['Pclass'] == 3].head(3)
data = {'Name': ['Chulmin', 'Eunkyung','Jinwoong','Soobeom'],
'Year': [2011, 2016, 2015, 2015],
'Gender': ['Male', 'Female', 'Male', 'Male']
}
data_df = pd.DataFrame(data, index=['one','two','three','four'])
data_df
# data_df 를 reset_index() 로 새로운 숫자형 인덱스를 생성
data_df_reset = data_df.reset_index()
# rename(columns={ '기존 이름' : '바꿀 이름'}) : 컬럼명 변경
data_df_reset = data_df_reset.rename(columns={'index':'old_index'})
data_df_reset
# index 값에 1을 더해서 0이 아닌 1부터 시작하는 새로운 index값 생성
data_df_reset.index = data_df_reset.index + 1
# key값은 각자 바꾸는건 불가능하지만 전체 적용해서 바꾸는 건 가능 (위 코드는 전체에 +1)
data_df_reset
data_df
data_df.iloc[0,0] # 컬럼명으로 불러올 수 없음
# 아래 코드는 오류 발생
# data_df.iloc[0, 'Name']
# data_df.iloc['one', 0]
data_df.loc['one','Name'] # 컬럼명이 아닌 수치를 넣으면 오류
# 아래 코드는 오류
#data_df_reset.loc[0, 'Name']
data_df_reset
# iloc의 경우 (수치기반)
data_df_reset.iloc[1,0]
# 왼쪽에 1,2,3,4는 자동으로 부여된 인덱스가 아닌 내가 설정한 값이므로 수치가 아니라 명칭이다
# 그러므로 iloc[1,0]은 one이 아니라 two
# loc의 경우 (명칭기반)
data_df_reset.loc[1,'Name']
# loc[1, 'Name']에서의 1은 숫자가 아닌 명칭! 1 인덱스라는 뜻이 아니다!!
# 명칭기반 loc에서는 마지막 값까지 가저옴(명칭 이므로)
data_df_reset.loc[1:2, 'Name']
# 위 데이터와 비교해서 봐두기
data_df.loc['one':'two', 'Name']
titanic_df = pd.read_csv('titanic_train.csv')
titanic_boolean = titanic_df[titanic_df['Age'] > 60]
print(type(titanic_boolean))
titanic_boolean
# 불린 인덱싱의 리턴값은 DataFrame이므로 원하는 칼럼만 추출 가능
titanic_df[titanic_df['Age'] > 60][['Name', 'Age']].head(3)
# 60세 이상의 이름과 나이만 가져와
# loc 활용해서 조건 걸기
titanic_df.loc[titanic_df['Age'] > 60, ['Name','Age']].head(3)
# 논리연산 가능
# and : & / or : | / not : ~
titanic_df[(titanic_df['Age'] > 60) & (titanic_df['Pclass']==1) & (titanic_df['Sex']=='female')]
cond1 = titanic_df['Age'] > 60
cond2 = titanic_df['Pclass']==1
cond3 = titanic_df['Sex']=='female'
titanic_df[ cond1 & cond2 & cond3]
titanic_df.head(3)
# sort_values() : 정렬
titanic_sorted = titanic_df.sort_values(by=['Name'])
titanic_sorted.head(3)
# ascending = False 옵션으로 내림차순 정렬(default는 True. 오름차순)
titanic_sorted = titanic_df.sort_values(by=['Pclass','Name'], ascending=False)
titanic_sorted.head(3)
# count() 집계함수
titanic_df.count()
# mean() 평균함수
titanic_df[['Age', 'Fare']].mean()
titanic_groupby = titanic_df.groupby(by='Pclass')
print(type(titanic_groupby))
# groupby - count() 적용
titanic_groupby = titanic_df.groupby('Pclass').count()
titanic_groupby
# select count('PassengerId'), count('Survived') from titanic_df group by 'Pclass'
titanic_groupby = titanic_df.groupby('Pclass')[['PassengerId', 'Survived']].count()
titanic_groupby
# Pclass로 groupby된 Age 컬럼의 max와 min 출력
titanic_df.groupby('Pclass')['Age'].agg([max, min])
# 딕셔너리를 이용해 다양한 aggreagtion 함수 적용
agg_format = {'Age':'max', 'SibSp':'sum', 'Fare':'mean'}
titanic_df.groupby('Pclass').agg(agg_format)
# groupby는 항상 집계함수와 같이 사용
titanic_df.isna().head(3)
# isna()
# True : 1의 합
titanic_df.isna().sum()
# 반환받아 다시 넣거나 fillna('값', inplace=True)
titanic_df['Cabin'] = titanic_df['Cabin'].fillna('C000')
titanic_df.head(3)
# 평균값으로 처리
titanic_df['Age'] = titanic_df['Age'].fillna(titanic_df['Age'].mean())
titanic_df['Embarked'] = titanic_df['Embarked'].fillna('S')
titanic_df.isna().sum()
def get_square(a):
return a**2
print('3의 제곱은: ', get_square(3))
# 함수명 = lambda 인자 : 리턴값
lambda_square = lambda x : x ** 2
print('3의 제곱은: ', lambda_square(3))
# 파이썬의 map함수 활용
# 리스트를 함수에 넣고 돌려서 다시 리스트로 반환
a = [1,2,3]
squares = map(lambda x : x ** 2, a)
list(squares)
titanic_df['Name_len'] = titanic_df['Name'].apply(lambda x : len(x))
titanic_df[['Name','Name_len']].head(3)
# 여러개의 컬럼을 가져오니까 리스트 값을 가져와야 해서 대괄호 두개
# if 조건문으로 가져오기
titanic_df['Child_Adult'] = titanic_df['Age'].apply(lambda x : 'Child' if x <= 15 else 'Adult')
titanic_df[['Age', 'Child_Adult']].head(8)
titanic_df['Age_cat'] = titanic_df['Age'].apply(
lambda x : 'Child' if x<=15 else('Adult' if x<=60 else 'Elderly'))
titanic_df['Age_cat'].value_counts()
# 나이에 따라 세분화딘 분류를 수행하는 함수 생성
# 위 처럼 lambda로 구분하는 것보다 함수를 활용하는게 더 깔끔
def get_category(age):
cat = ''
if age <= 5: cat = 'Baby'
elif age <= 12: cat = 'Child'
elif age <= 18: cat = 'Teenager'
elif age <= 25: cat = 'Student'
elif age <= 35: cat = 'Young Adult'
elif age <= 60: cat = 'Adult'
else : cat = 'Elderly'
return cat
# lambda 이용해서 위 함수에서 하나씩 꺼내오기
# lambda 식에 위에서 생성한 get_category( ) 함수를 반환값으로 지정.
# get_category(X)는 입력값으로 ‘Age’ 컬럼 값을 받아서 해당하는 cat 반환
titanic_df['Age_cat'] = titanic_df['Age'].apply(lambda x : get_category(x))
titanic_df[['Age', 'Age_cat']].head()