넘파이 기초

import numpy as np
array = np.array([1,2,3],[4,5,6])    #(2,3) 행렬 생성
sequence_array = np.arange(10)    #[0,1,2,3,4,5,6,7,8,9] 배열 생성
zero_array = np.zeros((2,2))     #(2,2) 영행렬 생성, dtype 바꿀 수 있음
one_array = np.ones((2,2))     #(2,2) 원소 1인 행렬 생성, dtype 바꿀 수 있음
array2 = array.reshape(1,6)    #array행렬의 형태를 (1,6)으로 변환, -1을 넣으면 행이나 열의 크기에 맞춰 자동으로 변환

인덱싱(Indexing), 슬라이싱(slicing)

array[row, col]    #row, col은 0부터 시작, 음수 값은 뒤에서 부터 접근, -1은 맨 뒷 값
array[row][col]    #위와 동일한 코드
array[:]     #행렬 전체 선택
array[1:2]    #1행 1열 값 선택, 열은 col-1 값 적용
array[0:2, 0:3]    # (0~1, 0~2)에 해당하는 원소 선택

array[array > 5]    #boolean 인덱싱, array의 원소 중 5보다 큰 값들 선택
boolean_indexes = np .array([False , False , False , False, False , True, True, True , True]) 
array3 = array1d[boolean_indexes]    #True에 해당하는 원소들 선택

정렬 - sort(), argsort()

org_array = np ,array([ 3, 1, 9, 5)) 
sort_array1 = np ,sort(org_array)    #[1,3,5,9]로 정렬됨
sort_array1_desc = np.sort(org_array)[ ::-1]   #[9,5,3,1] 순으로 내림차순 정렬

sort_array2d_axis0 = np .sort(array2d , axis=0)    #행 방향 정렬

sort_array2d_axis1 = np.sort(array2d , axis=1)    #열 방향 정렬

sort _indices = np. argsort (org_array )     #[1,0,3,2] 정렬 된 상태의 인덱스를 반환

Untitled

행렬 내적, 전치 행렬

dot-product = np.dot(A , B)    #행렬 A, B를 내적

transpose_mat = np .transpose(A)   #행렬 A의 전치행렬

판다스 기초

import pandas as pd

#파일 읽기
titanic_df = pd.read_csv('train.csv')
print('titanic 변수 type: ', type(titanic_df))
titanic_df

titanic_df.info()   #df의 메타 데이터 출력
titanic_df.describe()

#Pclass의 개수 출력
value_counts=titanic_df['Pclass'].value_counts()
print(value_counts)

판다스 DataFrame과 넘파이 ndarray, 파이썬 list, dict와 상호 변환

import numpy as np
                            #DataFrame과 리스트, 딕셔너리 넘파이 ndarray 상호 변환
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)

dict = {'col1':[1,11], 'col2':[2,22],'col3':[3,33]}
df_dict = pd.DataFrame(dict)
print('딕셔너리로 만든 DataFrame:\\n',df_dict)
#key값은 칼럼명, value는 각 칼럼 데이터로 매핑

array3= df_dict.values
print('df_dict.values 타입: ', type(array3), 'df_dict.values shape: ',array3.shape)
print(array3)

list3 = df_dict.values.tolist()
print('\\ndf_dict.values.tolist() 타입: ',type(list3))
print(list3)

dict3 = df_dict.to_dict('list')
print('\\ndf_dict.todict() 타입: ',type(dict3))
print(dict3)

칼럼 추가, 삭제

titanic_df['Age_0'] = 0
titanic_df.head()

#DataFrame .drop(labels=None , axis=Ø, index=None , columns=None, level=None, inplace=False, errors=’raise ’) 
#반환 값이 None이 되어서 titanic_drop_df에는 아무값도 없음.
titanic_drop_df = titanic_df.drop('Age_0', axis=1, inplace=True)    #열 기준 삭제
titanic_drop_df.head()

pd.set_option('display.width', 1000)
pd.set_option('display.max_colwidth', 15)
print(titanic_df.head())

titanic_df.drop([0,1,2], axis=0, inplace=True)   #행 기준 삭제
print(titanic_df.head())

Index 객체, 인덱싱 iloc, loc

indexes = titanic_df.index
print(indexes)
print('Index 객체 array 값: \\n', indexes.values)

titanic_reset_df = titanic_df.reset_index(inplace=False)
titanic_reset_df.head()
#Series에 reset_index()를 적용하고 나면 type이 DataFrame으로 바뀜
print(type(titanic_reset_df))  

titanic_df[0:10]

titanic_df[titanic_df['Pclass'] == 3].head()    #boolean indexing

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 = data_df.reset_index()
data_df_reset =data_df_reset.rename(columns={'index':'old_index'})
data_df_reset.index = data_df_reset.index + 1
data_df_reset

data_df.iloc[0,0]
data_df.iloc[0,'Name']     #명칭 입력 불가

data_df.loc['one','Name']
data_df.loc[1,'Name']   #정수형 인덱스값 사용 불가

titanic_df[titanic_df['Age'] > 60][['Name','Age']].head (3) 
titanic_df.loc[titanic_df['Age'] > 60,['Name','Age']].head (3)

aggregation 함수