728x90
반응형
판다스
- 판다스의 핵심 개체는 DataFrame이다.
- DataFrame은 여러 개의 행과 열로 이뤄진 2차원 데이터를 담는 데이터 구조체다.
- Index
- Index는 RDBMS의 PK(Primary Key)처럼 개별 데이터를 고유하게 식별하는 Key 값이다.
- Series와 DataFrame은 모두 Index를 key 값으로 가지고 있다.
- Series는 칼럼이 하나뿐인 데이터 구조체
- DataFrame은 칼럼이 여러 개인 데이터 구조체
- DataFrame은 여러 개의 Series로 이뤄졌다고 할 수 있다.
import pandas as pd
titanic_df = pd.read_csv(r'train.csv')
print('titanic 변수 type : ',type(titanic_df))
titanic_df
- 891개의 row 데이터와 12개의 특성
DataFrame 칼럼의 타입, Null 데이터 개수, 데이터 분포도 등의 메타 데이터 조회 가능
- info(), describe()
titanic_df.info() # 총 데이터 건수, 데이터 타입, Null 건수를 알 수 있다.
- 총 데이터 건수, 데이터 타입, Null 건수를 알 수 있다.
titanic_df.describe() # 컬러별 숫자형 데이터값의 n-percentile 분포도, 평균값, 최댓값, 최솟값을 나타냄
- count는 Not Null인 데이터 건수, mean은 전체 데이터의 평균값, std는 표준편차, min은 최솟값, max는 최댓값
- PassengerID 칼럼은 승객 ID를 식별하는 칼럼 1~891까지 숫자 할당
# VALUE_COUNTS() 메서드 해당 칼럼값의 유형과 건수 확인
value_counts = titanic_df['Pclass'].value_counts()
print(value_counts)
- 해당 칼럼값의 유형과 건수 확인 가능
- Pclass값 3이 491개, 1이 216개, 2이 184개
- 많은 건수부터 정렬되어 값을 반환한다.
DataFrame과 리스트, 딕셔너리, 넘파이 ndarray 상호 변환
- 기본적으로 DataFrame은 파이썬의 리스트, 딕셔너리, 넘파이 ndarray 등 다양한 데이터로부터 생성 가능
- DataFrame은 반대로 파이썬으 리스트, 딕셔너리 그리고 넘파이 ndarray 등으로 변환될 수 있다.
DataFrame의 칼럼 데이터 세트 생성과 수정
# DataFrame의 칼럼 데이터 세트 생성과 수정
titanic_df['Age_0'] = 0
titanic_df.head(3)
기존 칼럼 Series의 데이터를 이용해 새로운 칼럼 Series 만듬
titanic_df['Age_by_10'] = titanic_df['Age']*10
titanic_df['Family_No'] = titanic_df['SibSp'] + titanic_df['Parch']+1
titanic_df
DataFrame 데이터 삭제
- 데이터 삭제는 drop() 메서드를 이용한다.
- DataFrame.drop(labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise')
- 가장 중요한 파라미터는 labels, axis, inplace
- axis 값에 따라서 특정 칼럼 또는 특정 행을 드롭한다.
- axis 0 은 로우 방향 축, axis 1은 칼럼 방향 축이다.
Age_0 칼럼 삭제
titanic_drop_df = titanic_df.drop('Age_0', axis=1)
titanic_drop_df
생성한 칼럼 전부 삭제
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)
axis=0, index 0,1,2 삭제
pd.set_option('display.width', 1000)
pd.set_option('display.max_colwidth', 15)
print('#### before axis 0 drop ####')
print(titanic_df.head(3))
titanic_df.drop([0,1,2], axis=0, inplace=True)
print('#### after axis 0 drop ####')
print(titanic_df.head(3))
DataFrame을 변경하는 방식
- axis = DataFrame의 로우를 삭제할 때는 axis=0, 칼럼을 삭제할 때는 axis=1으로 설정
- 원본 DataFrame은 유지하고 드롭된 DataFrame을 새롭게 객체 변수로 받고 싶다면 inplace=False로 설정(디폴트 값이 False)
- 원본 DataFrame에 드롭된 결과를 적용할 경웨는 inplace=True를 적용
- 원본 DataFrame에서 드롭된 DataFrame을 다시 원본 DataFrame 객체 변수로 할당하면 원본 DataFrame에서 드롭된 결과를 적용할 경우와 같다.
Index 객체
- 판다스 Index 객체는 RDBMS의 PK(Primary Key)와 유사하게 DataFrame, Series의 레코드를 고유하게 식별하는 객체다.
타이타닉 데이터 index 객체 추출
# 원본 파일 다시 로딩
titanic_df = pd.read_csv('train.csv')
# Index 객체 추출
indexes = titanic_df.index
print(indexes)
# Index 객체를 실제 값 array로 변환
print('Index 객체 array값 : \n', indexes.values)
DataFrame 및 Series의 Index 객체는 함부로 변경할 수 없다.
indexes[0] = 5
reset_index() 메서드
# reset_index() 메서드 수행시 새롱운 인덱스를 연속 숫자 형으로 할당하며 기존 인덱스는 'index'라는 새로운 칼럼 명으로 추가된다.
titanic_reset_df = titanic_df.reset_index(inplace=False)
titanic_reset_df.head(3)
데이터 셀렉션 및 필터링
- 판다스와 넘파이 기능이 다른 경우도 많다.
- 넘파이의 경우 '[]' 연산자 내 단일 값 추출, 슬라이싱, 팬시 인덱싱, 불린 인덱싱을 통해 데이터를 추출한다.
- 판다스의 경우 ix[], iloc[], loc[] 연산자를 통해 동일한 작업을 수행한다.
DataFrame의 [] 연산자
- 넘파이에서 [] 연산자는 행의 위치, 열의 위치, 슬라이싱 범위 등을 지정해 데이터를 가져올 수 있다.
- DataFrame 바로 뒤에 있는 '[]'안에 들어갈 수 있는 것은 칼럼 명 문자, 인덱스로 변환 가능한 표현식이다.
DataFrame의 ix[] 연산자
- ix[]는 ix[0, 'Pclass']와 같이 행 위치 지정으로 인덱스값 0,열 위치 지정으로 칼럼 명인 'Pclass'를 입력해 원하는 위치의 데이터를 추출할 수 있다.
- ix[]의 행에 해당하는 위치 지정은 DataFrame의 인덱스값을 입력해야 한다.
- 열 위치 지정은 칼럼 명 뿐만 아니라 ix[0,2]와 같이 칼럼 명이 아닌 칼럼의 위치 값 지정도 가능하다.
data_df.ix[0,0]
data_df.ix['one', 0]
data_df.ix[3, 'Name']
data_df.ix[:2, [0,1]]
data_df.ix[0:3, ['Name', 'Year']]
명칭 기반 인덱싱과 위치 기반 인덱싱의 구분
- 명칭(label) 기반 인덱싱은 칼럼의 명칭을 기반으로 위치를 지정하는 방식. - '칼럼 명 '같이 명칭으로 열 위치를 지정하는 방식
- 위치(Position) 기반 인덱싱은 0을 출발점으로 하는 가로축, 세로축 좌표 기반의 행과 열 위치를 기반으로 데이터를 지정한다.
DataFrame iloc[] 연산자
- iloc[]는 위치 기반 인덱싱만 허용하기 때문에 행과 열 값으로 integer 또는 integer형의 슬라이싱, 팬시 리스트 값을 입력해줘야 한다.
data_df.iloc[0,0]
DataFrame loc[] 연산자
- 명칭 기반으로 데이터를 추출한다.
- 행 위치에는 DataFrame index 값을
- 열 위치에는 칼럼 명을 입력해 준다.
data_df.loc['one', 'Name']
불린 인덱싱
- [], ix[], loc[]에서 공통으로 지원
- iloc[]는 정수형 값이 아닌 불린 값에 대해서는 지원하지 않기 때문에 불린 인덱싱이 지원되지 않는다.
# 데이터 새롭게 로드
titanic_df = pd.read_csv('train.csv')
titanic_boolean = titanic_df[titanic_df['Age'] > 60]
print(type(titanic_boolean))
titanic_boolean
- datatype은 DataFrame이다.
# 60세 이상인 승객의 나이와 이름만 추출
titanic_df[titanic_df['Age']>60][['Name','Age']].head(3)
정렬, Aggregation 함수, GroupBy 적용
- DataFrame과 Series의 정렬은 sort_values() 메서드를 이용하면 된다.
- ascending=False로 설정하면 내림차순
- ascending=True로 설정하면 오름차순 default는 True다.
Name 칼럼으로 오름차순 정렬
titanic_sorted = titanic_df.sort_values(by=['Name']) # Name 칼럼으로 오름차순
titanic_sorted.head(3)
Aggregation 함수 적용
- DataFrame에서 min(), max(), sum(), count()와 같은 aggregation 함수의 적용은 RDBMS SQL의 aggregation 함수 적용과 유사하다.
titanic_df.count()
groupby() 적용
- DataFrame의 groupby() 사용 시 입력 파라미터 by에 칼럼을 입력하면 대상 칼럼으로 groupby된다.
- DataFrame에 groupby()를 호출하면 DataFrameGroupBy라는 또 다른 형태의 DataFrame을 반환한다.
# groupby - pclass 칼럼 기준으로
titanic_groupby = titanic_df.groupby(by='Pclass')
print(type(titanic_groupby))
titanic_groupby = titanic_df.groupby('Pclass').count()
titanic_groupby
결손 데이터(Missing Data) 처리하기
- 결손 데이터는 칼럼에 값이 없는, NULL인 경우를 의미하며, 이를 넘파이의 NaN으로 표시한다.
- 기본적으로 머신러닝 알고리즘은 이 NaN 값을 처리하지 않으므로 이 값을 다른 값으로 대체해야 한다.
- NaN 값은 평균, 총합 등의 함수 연산 시 제외가 된다.
- NaN 여부를 확인하는 API는 isna()이며, NaN 값을 다른 값으로 대체하는 API는 fillna()이다.
isna()
titanic_df.isna().head(3) # 모든 칼럼의 값이 True, False로 알려준다.
결손 데이터 개수 isna() 결과에 sum() 함수를 추가해 구하기
titanic_df.isna().sum()
fillna()로 결손 데이터 대체
titanic_df['Cabin'] = titanic_df['Cabin'].fillna('C000')
titanic_df.head(3)
남은 결손 데이터도 대체
- 'Age' 칼럼 NaN 값을 평균 나이로
- 'Embarked' 칼럼의 NaN 값을 'S'로 대체
titanic_df['Age'] = titanic_df['Age'].fillna(titanic_df['Age'].mean())
titanic_df['Embarked'] = titanic_df['Embarked'].fillna('S')
titanic_df.isna().sum()
728x90
반응형
최근댓글