'replacing generic values using replace() method'에 해당되는 글 1건

  1. 2016.12.11 [Python pandas] 결측값, 원래 값을 다른 값으로 교체하기(replacing generic values) : replace() 4

지난번 포스팅에서는 Python pandas의

 

 - fillna() method를 사용한 결측값 대체

 - dropna() method를 사용한 결측값 있는 행, 열 제거

 - interpolate() method를 사용한 결측값 보간

 

하는 방법을 알아보았습니다.

 

이번 포스팅에서는 Python pandas의 replace() method를 사용해서

 

 - 결측값 혹은 원래의 값을 다른 값으로 교체(replacing generic values)

 - List 를 다른 List로 교체

 - mapping dict 로 교체

 - DataFrame의 특정 칼럼 값 교체

 

하는 방법을 소개하겠습니다.

 

fillna() 를 사용한 결측값 대체와 replace()를 사용한 결측값 교체가 유사한면이 있구요, 다만 replace() 는 결측값 말고도 모든 값을 대상으로 할 수 있고, list, mapping dict 등으로 좀더 유연하고 포괄적으로 사용할 수 있는 장점이 있습니다.

 

 

 

 

replace() method를 가지고 결측값, 실측값 모두를 대상으로 교체(replacement)하는 예를 들어보겠습니다.  필요한 모듈을 importing하고, 결측값을 포함한 간단한 Series 먼저 시작하겠습니다.

 

 

In [1]: import pandas as pd


In [2]: import numpy as np


In [3]: from pandas import DataFrame, Series

 

In [4]: ser = Series([1, 2, 3, 4, np.nan])

 

In [5]: ser

Out[5]:

0    1.0
1    2.0
2    3.0
3    4.0
4    NaN
dtype: float64

 

 

 

 

  (1) 결측값, 실측값을 다른 값으로 교체하기 : replace(old_val, new_val)

 

 

# replacing a value with other value

In [6]: ser.replace(2, 20)

Out[6]:

0     1.0
1    20.0
2     3.0
3     4.0
4     NaN
dtype: float64

 

# replacing missing value(NaN) with other value

In [7]: ser.replace(np.nan, 5)

Out[7]:

0    1.0
1    2.0
2    3.0
3    4.0
4    5.0
dtype: float64

 

 

 

 

 

  (2) list 를 다른 list 값으로 교체하기 : replace([old1, old2, ...], [new1, new2, ...])

 

 

In [8]: ser

Out[8]:

0    1.0
1    2.0
2    3.0
3    4.0
4    NaN
dtype: float64

 

In [9]: ser.replace([1, 2, 3, 4, np.nan], [6, 7, 8, 9, 10])

Out[9]:

0     6.0
1     7.0
2     8.0
3     9.0
4    10.0
dtype: float64

 

 

 

 

  (3) mapping dict 로 원래 값, 교체할 값 매핑 : replace({old1 : new1, old2: new2})

 

 

In [10]: ser

Out[10]:

0    1.0
1    2.0
2    3.0
3    4.0
4    NaN
dtype: float64

 

In [11]: ser.replace({1: 6,

    ...: 2: 7,

    ...: 3: 8,

    ...: 4: 9,

    ...: np.nan: 10})

Out[11]:

0     6.0
1     7.0
2     8.0
3     9.0
4    10.0
dtype: float64

 

 

 

 

  (4) DataFrame의 특정 칼럼 값 교체하기 : df.replace({'col1': old_val}, {'col1': new_val})

 

DataFrame 의 값을 교체하려면 dict { } 안에 원래와 교체할 'column name'과 'value' 를 짝을 이루어서 매핑해주면 됩니다.

 

 

In [13]: df = DataFrame({'C1': ['a_old', 'b', 'c', 'd', 'e'],

    ...: 'C2': [1, 2, 3, 4, 5],

    ...: 'C3': [6, 7, 8, 9, np.nan]})


In [14]: df

Out[14]:

      C1  C2   C3
a_old   1  6.0
1      b   2  7.0
2      c   3  8.0
3      d   4  9.0
4      e   5  NaN

 

In [15]: df.replace({'C1': 'a_old'}, {'C1': 'a_new'})

Out[15]:

      C1  C2   C3
a_new   1  6.0
1      b   2  7.0
2      c   3  8.0
3      d   4  9.0
4      e   5  NaN


In [16]: df.replace({'C3': np.nan}, {'C3': 10})

Out[16]:

      C1  C2    C3
0  a_old   1   6.0
1      b   2   7.0
2      c   3   8.0
3      d   4   9.0
4      e   5  10.0

 

 

 

이상으로 Python pandas의 replace() method를 사용해서 결측값, 원래 값을 다른 값으로 교체하기 소개를 마치겠습니다.

 

결측값을 그룹별로 그룹별 평균으로 대체하기는 http://rfriend.tistory.com/402 를 참고하세요. 


많은 도움이 되었기를 바랍니다.

 

 

 

728x90
반응형
Posted by Rfriend
,