Python/[코칭스터디 9기] 인공지능 AI 기초 다지기

[인공지능(AI) 기초 다지기] 4. 기초튼튼, 수학튼튼 (1)

김초송 2023. 2. 14. 19:52

https://www.boostcourse.org/ai100/joinLectures/233689 

 

인공지능(AI) 기초 다지기

부스트코스 무료 강의

www.boostcourse.org

3. Pandas I / 딥러닝 학습방법 이해하기

 

1) pandas 1

 

- Pandas

  • 구조화된 데이터의 처리를 지원하는 Python 라이브러리
  • 고성능 Array 계산 라이브러리인 Numpy와 통합
  • 인덱싱, 연산 함수, 전처리 함수 등 제공
  • pandas = numpy wrapper
import pandas as pd # 라이브러리 호출

df_data = pd.read_csv(data_url, sep='\s+', header=None)

df_data.values # type은 numpy
  • sep='\s+' : seperate는 데이터를 나누는 기준, 빈 칸으로 나눠서 다 가져와라
  • header : 첫 행이 컬럼이름이냐? 

 

- Pandas의 구성

  • Series
    • Numpy에서 하나의 벡터 (=Column Vector)
    • DataFrame 중 하나의 Column에 해당하는 데이터 모음 Object
    • List나 Dict 타입에서 Series 타입으로 변환할 수 있음
    • 인덱스 중복 가능
    • 인덱스로 값 접근
  • DataFrame
    • Data Table 전체를 포함하는 Object
    • Series Object들의 모음
    • 2차원 Matrix
    • row와 column의 주소를 알면 접근 가능
    • 컬럼명으로 특정 데이터만 뽑아올 수 있음
    • numpy의 subclass
# DataFrame에서 Series 추출
df.column_name
df['column_name']

 

- DataFrame 접근방법

  • loc : index location, 인덱스 이름
  • iloc : index position, 인덱스 번호
df.loc[index] # index의 행 추출
df['column_name'].iloc[index] # Series에서 데이터 추출

s = pd.DataFrame(np.nan, index=[49, 48, 47, 46, 45, 1, 2, 3, 4, 5]
s.loc[:3]
# 49, 48, 47, 46, 45, 1, 2, 3
s.iloc[:3]
# 49, 48, 47

 

- Selection

  • [] 안에 str이면 컬럼, slicing이면 로우 출력
  • ['str'][:] : 두 개 함께 사용하면 해당 컬럼의 row index 해당 값만 출력
# Basic
df[['name', 'street']][:2]

# loc
df.loc[[211829, 320563], ['name', 'street']] # column, index name

# iloc
df.iloc[:2, :2] # [column, index] number

 

- Drop

  • 행 삭제
  • index number로 drop
  • 한 개 이상일 경우 list로 값 입력
  • 컬럼 삭제는 del or drop(axis=1)
  • 판다스는 원본 데이터를 쉽게 삭제 안함 -> inplace=True 설정
df.drop([1, 2, 3]) # index number 1, 2, 3인 행 삭제
df.drop('city', axis=1) # city 컬럼 삭제

 

- Operation

  • Series는 index가 일치하는 데이터끼리 연산
  • DataFrame은 column과 index 모두 일치하는 데이터끼리 연산
  • 겹치는 데이터가 없으면 NaN 반환
    fill_value=0 : NaN값을 0으로
  • .add, sub, div, mul
  • Series 와 DataFrame 의 연산은 컬럼을 기준으로 broadcasting 발생
    axis=0이면 row broadcasting 실행

 

- Lambda / Map / Apply

  • Map
    • Series 데이터에서 사용 가능 (Series element 단위에 적용하는 함수)
    • function 대신 dict, sequence형 자료 등으로 대체 가능
    • 숫자 <-> 문자 형변환에도 많이 쓰임
df["sex_code"] = df.sex.map({"male":0, "female":1})
df.sex.replace({"male":0, "female":1})
df.sex.replace(["male", "female"], [0, 1])
  • Apply
    • Series 전체에 해당 함수 적용
    • 입력값이 Seires 데이터로 받아서 handling
    • DataFrame 여러가지 통계 자료를 볼 때 많이 사용
    • scalar 값 외의 series 값 반환도 가능
f = lambda x : x.max() - x.min() # 컬럼에서 가장 큰 값 - 컬럼에서 가장 작은 값
df.info.apply(f)
# 시리즈 (각 컬럼 별로 반환값) 출력

def f(x):
    return Series([x.min(), x.max()], index=['min', 'max'])
    
df_info.apply(f)
# DataFrame 출력 (각 컬럼별로 series를 리턴하기 때문에)
  • Applymap
    • Series의 element 단위로 함수 적용
    • Series 단위에 apply 시킬 때와 같은 효과
f = lambda x : -x
df_info.applymap(f)
# DataFrame 반환

 

- Label Encoding

np.array(dict(enumerate(df["race"].unique()))) # dict 타입으로 index
# array({0: 'white', 1: 'other', 2: 'hispanic', 3: 'black'}, dtype=object)

value = list(map(int, np.array(list(enumerate(df["race"].unique())))[:, 0].tolist()))
key = np.array(list(enumerate(df["race"].unique())), dtype=str)[:,1].tolist()

value, key
# ([0, 1, 2, 3], ['white', 'other', 'hispanic', 'black'])