garret

[Python] pandas.Series.str.replace 함수 본문

Programming/Python

[Python] pandas.Series.str.replace 함수

_Sun_ 2023. 7. 5. 22:42

데이터 분석을 할 경우, 카테고리형 변수, 또는 string을 전처리할 경우가 종종 생긴다. 

사실 이전까지는 얄팍하게 알고 사용해온 감이 없지 않아 있어서, 이번 기회에 파라미터를 어떤 걸 쓸 수 있는지 공부해 보았다. 

 

str.replace() 함수 정의


Series.str.replace(pat,rept, n=-1, case=None, flags=0, regex=False)

Series나 index에서 패턴이나 regex(정규식)를 교체하는 함수

str.replace(),  re.sub()와 동일한 기능 수행

 

 

아웃풋

Series 나 object의 인덱스

 

 

 

파라미터 구성


pat : 기존 str 이나 regex

repl : 대체 str 

n : 시작에서 부터 대체하고자 하는 개수(int). 디폴트 -1(전체)

case : repl이 case sensitive인지 판별(bool).

  • True라면, case sensitive. (pat이 str이라면 디폴트)
  • False라면, case insensitive
  • pat이 compiled regex라면 사용불가

flags : Regex module flags(int). pat이 compiled regex이면 사용 불가. 디폴트 0 (no flags)

regex : passed-in pattern이 정규식인지 판별

  • True라면, passed-in pattern을 정규식으로 가정
  • False라면, pattern을 문자그대로 string으로 취급
  • pat이 compiled regex이거나 repl이 callable이라면 사용불가

 

 

예시


>>> pd.Series(['foo', 'fuz', np.nan]).str.replace('f.', 'ba', regex=True)
0    bao
1    baz
2    NaN
dtype: object

regex = True로 설정하여, pat을 regex로 compiled. 즉 f로 시작하는 부분을 ba로 변환함

 

>>> pd.Series(['f.o', 'fuz', np.nan]).str.replace('f.', 'ba', regex=False)
0    bao
1    fuz
2    NaN
dtype: object

regex = False로 설정하면, 'f.'을 단순 str로 인식해서 'f.'이 포함된 부분만 ba로 변환. 

 

 

 

 

Reference

 

pandas.Series.str.replace — pandas 2.0.3 documentation

Regex module flags, e.g. re.IGNORECASE. Cannot be set if pat is a compiled regex.

pandas.pydata.org