[Python.Pandas] Map 함수 실전편 + .replace함수 사용하기

2020. 12. 20. 05:00Python과 머신러닝/Pandas 데이터 분석

0. 이전 포스트

 

[Python.Pandas] Lambda함수와 Map함수 이해하기 - Series.map

1. Lambda란? In [1]:def f1(x,y): return x+y In [2]:f1(1,2) Out[2]:3 In [3]:f2=lambda x,y:x+y In [4]:f2(1,2) Out[4]:3 Lambda란 함수를 한 줄로 표현하는 익명 함수 기법이다. lisp 언어에서 시작된 기법으..

coding-grandpa.tistory.com

 

1. wget으로 데이터 다운로드하여 .unique로 데이터 종류 분석하기

In [1]:import wget url = 'https://raw.githubusercontent.com/rstudio/Intro/master/data/wages.csv' 
        wget.download(url)
Out[1]:'wages.csv'

In [2]:df = pd.read_csv("./wages.csv") 
        df.head()
Out[2]:
    earn            height  sex     race    ed  age
0   79571.299011    73.89   male    white   16  49
1   96396.988643    66.23   female  white   16  62
2   48710.666947    63.77   female  white   16  33
3   80478.096153    63.22   female  other   16  95
4   82089.345498    63.08   female  white   17  43

In [3]:df.sex.unique()
Out[3]:array(['male', 'female'], dtype=object)

 

2. 함수 정의를 통한 data encoding 

In [22]:def change_sex(x): 
            return 0 if x=='male' else 1

In [23]:df['sex_code'] = df.sex.map(change_sex) 
        df
Out[23]:
        earn            height   sex     race     ed    age   sex_code
0       79571.299011    73.89    male    white    16    49    0
1       96396.988643    66.23    female  white    16    62    1
2       48710.666947    63.77    female  white    16    33    1
3       80478.096153    63.22    female  other    16    95    1
4       82089.345498    63.08    female  white    17    43    1
        ...	...	...	...	...	...	...
1374    30173.380363    71.68    male    white    12    33    0
1375    24853.519514    61.31    female  white    18    86    1
1376    13710.671312    63.64    female  white    12    37    1
1377    95426.014410    71.65    male    white    12    54    0
1378    9575.461857     68.22    male    white    12    31    0
1379 rows × 7 columns
  • change_sex라는 함수는 male은 0으로, female은 1로 바꿔주는 함수이다.
  • 이전 포스트에서 정리했듯이 이 함수를 Series.map의 Parameter로 전달하면, Series의 각 value를 해당 함수로 변환시킨다.
    2020/12/19 - [Python과 머신러닝/Pandas 데이터 분석] - [Python.Pandas] Lambda함수와 Map함수 이해하기 - Series.map
  • 그렇기 때문에 df.sex.map(change_sex)라는 함수는, df.sex라는 Series의 값을 change_sex 함수를 통해 값을 변형해라는 의미로 전달된다.
  • 이 결과값을 다시 df['sex_code']에 담았기 때문에, df를 출력해보면 sex_code라는 Series가 추가된 것을 볼 수 있고, male인 경우에는 0, female인 경우에는 1로 잘 담긴 것을 확인할 수 있다.
  • Map 함수가 중요한 이유는, male/female이라는 string data를 가지고는 Pandas나 Python의 어떤 라이브러리를 가지고도 기계학습을 시키기가 제한되거나 불가능하다.
  • Data를 정수형/연속형 데이터로 변형시켜줘야 컴퓨터는 이러한 숫자 데이터를 가지고 학습을 하고, 미래를 예측하는 모델링을 할 수 있는데, 컴퓨터에게 'male', 'female'은 너무 어려운 값이다.
  • 그렇기 때문에 대부분의 경우 데이터 전처리 과정에서 이러한 categorical data를 0/1/2/... 등등으로 encoding 해주는 과정이 필수적이고, 그러기 위해서는 .map 함수가 필수적으로 사용된다. 꼭 이해하고 있어야 한다.

 

3. Dict를 통한 data encoding

In [24]:df['sex_code'] = df.sex.map({'male':0, 'female':1}) 
        df
Out[24]:
        earn            height   sex     race     ed    age   sex_code
0       79571.299011    73.89    male    white    16    49    0
1       96396.988643    66.23    female  white    16    62    1
2       48710.666947    63.77    female  white    16    33    1
3       80478.096153    63.22    female  other    16    95    1
4       82089.345498    63.08    female  white    17    43    1
        ...	...	...	...	...	...	...
1374    30173.380363    71.68    male    white    12    33    0
1375    24853.519514    61.31    female  white    18    86    1
1376    13710.671312    63.64    female  white    12    37    1
1377    95426.014410    71.65    male    white    12    54    0
1378    9575.461857     68.22    male    white    12    31    0
1379 rows × 7 columns
  • 위와 같은 작업을 함수가 아닌 dict를 통해서도 할 수 있다.
  • dict의 key를 input 값, dict의 value를 output 값으로 지정해준다면, 원하는 대로 male은 0, female은 1로 encoding 되는 것을 확인할 수 있다.
  • 꼭 함수 정의를 하지 않더라도, dict type을 통해서도 동일하게 가능하다는 것을 보여주는 예시이다.

 

4. .replace를 사용한 data encoding

In [25]:df.sex.replace({'male':0, 'female':1}) 
        df.sex.replace(['male', 'female'], [0,1])
Out[25]:
        0 0 
        1 1 
        2 1 
        3 1 
        4 1 
        .. 
        1374 0 
        1375 1 
        1376 1 
        1377 0 
        1378 0 
        Name: sex, Length: 1379, dtype: int64
        
  • .replace 함수는 .map 함수와 유사한 동작을 하고 In[25]와 같이 사용하여, encoding을 수행할 수 있다.

 

5. 관련 포스트

 

[Python.Pandas] DataFrame.apply, DataFrame.applymap

1. DataFrame.Apply - 하나의 Series가 아닌 전체 DataFrame에 함수를 적용하고 싶을 때 In [1]:from pandas import Series, DataFrame import pandas as pd import numpy as np In [2]:df = pd.read_csv("wages.c..

coding-grandpa.tistory.com

 

[Python.Pandas] Built-in Function 이해하기 - .describe()

1. DataFrame.describe 및 데이터 초기 분석 In [1]:from pandas import Series, DataFrame import pandas as pd import numpy as np In [2]:df = pd.read_csv('wages.csv') df.head(2).T Out[2]: 0 1 earn 79571...

coding-grandpa.tistory.com

 

반응형