DS_Feature Engineering

ParkJangSik·2021년 5월 7일
1

Codestates_DS

목록 보기
2/6

주제 : Feature Engineering

1. Feeture Engineering?

  • what?
    DF의 Feature들을 조합해서 새로운 Feature를 만드는 것
    ex) BMI 지수 = 몸무게/~~
  • why?
    더 좋은 퍼포먼스를 얻기 위해, 새롭고 의미있는 데이터를 제공하려고 하기 때문이다.

2. 과제 질문

  • read_csv에서의 설정 - thousands, names
  • 기존 DF에서 새로운 Feature 만들기
  • pandas에서 DataFrame 만들기
  • DataFrame내의 특정 자료 변환하기 - iloc, loc
  • DataFrame내의 특정 자료 변환하기 - apply 함수
  • DataFrame내의 특정 자료 변환하기 - 문자를 숫자로
  • DataFrame내의 특정 자료 변환하기 - replace, 딕셔너리, Null 값 넣기
  • DataFrame 합치기 및 특정 열 삭제 - concat, drop
  • Mean imputation으로 결측치 채우기

3. 과제 명령어 모음

(1) read_csv에서의 설정 - thousands, names

url=www.~~~
headers = ['a','b'~~]

df= pd.read_csv(url, names=headers , thousands= ',')

🌟 csv파일을 불러올 때 다양한 조건이 있다
🌟 names 조건을 통해 column을 설정할 수 있다.
🌟 thousands= ',' 설정을 통해 ,(콤마)를 없애고 문자열로 불러 오는 것을 사전에 방지할 수 있다.

(2) 기존 DF에서 새로운 Feature 만들기

student_card = pd.DataFrame({'ID':[20190103, 20190222, 20190531], 'name':['Kim', 'Lee', 'Jeong'] 
,'class':['H', 'W', 'S']}, index = ['a', 'b', 'c'])

🌟 '영업이익률2라는 새로운 Column을 만들 수 있다.

(3) pandas에서 DataFrame 만들기

df2 = pd.DataFrame({"구분":['18년','19년'], "종가":[101500,93800], "발행주식수":[137292497,137292497	],"시가총액":[13935188445500,12878036218600], "시장점유율":[62.0,63.5]})
df2

🌟 DataFrame을 직접 만들 때 사용한다.

(4) DataFrame내의 특정 자료 변환하기 - iloc, loc

df.dtypes

df.iloc[0,1] = 12578

🌟 df.dtypes를 통해 각 컬럼들의 형태를 알 수 있다.
🌟 인덱스번호로 각 데이터에 접근할 수 있는 iloc[]를 사용해서 값을 변경 할 수 있다.

iloc과 loc의 사용 방법, 차이

iloc과 loc을 사용한 값 변경

(5) DataFrame내의 특정 자료 변환하기 - apply 함수를 이용하여 콤마 없애기

def toint(string):
  return int(string.replace(',','')) 
  
  ## df['colname'].str.replace(',', '').astype(float) ##

for i in df.columns:
  if df[i].astype== str:
    df[i] = df[i].apply(toint)

df

🌟 replace함수를 이용해서 문자열의 ,를 없앨 수 있다
🌟 for문과 apply 함수를 이용해서 DF내의 각 컬럼들에 대해 ,를 없애준다.

🔥 for문에서 df4.columns를 사용할 수 있는 Tip!
🔥 apply함수는 다른 함수를 불러 옴 Tip!

df_tidy['value']=df_tidy['value'].apply(lambda x : x.replace(',','')) 

🌟 또 다른 방법으로 콤마를 제거하는 문법이다.
??????? (여기서 lambda x : x.~) 의 의미는????????

(6) DataFrame내의 특정 자료 변환하기 - 문자를 숫자로

df4=df4.apply(pd.to_numeric)
df4.dtypes

df4=df4['a'].apply(pd.to_numeric)

🌟 pd.to_numeric 함수를 통해 숫자형으로 변경 가능하다.
🌟 특정열만 선택해서 변경도 가능하다.

(7) DataFrame내의 특정 자료 변환하기 - replace, 딕셔너리, Null 값

import numpy as np
df7.replace({'당기순이익':1183},{'당기순이익': np.NaN})

🌟 numpy 라이브러리를 이용해서 null값을 불러온다
🌟 replace() 함수를 이용해서 값을 변환
🌟 딕셔너리 {'컬럼' : 데이터} 이용해서 변환할 데이터 선정

(8) DataFrame 합치기 및 특정 열 삭제 - concat, drop

df7= pd.concat([df4,df5],axis=1) 
df7

🌟 axis = 1 이 컬럼 기준이라는 의미이다.
🌟 axis=0은 행 기준

(9) Mean imputation으로 결측치 채우기

df7.fillna(df.mean())

df.where(pd.notnull(df),df.mean(),axis='columns') 

🌟 1일째는 결측값을 0으로 바꿔주는 것을 했었는데 평균값 등으로도 바꿔 줄 수 있다는 것을 알았다.

DataFrame의 특정 칼럼 값 교체하기

결측값 대체 이론 = imputation

결측값 대체 방법

profile
취준생

0개의 댓글