본문으로 바로가기

 

차례

1. 사용방법

2. 예제

 

 

 


 

 

 

파이썬이 제공하는 replace 함수'바꾸는' 기능이 있습니다.

엑셀의 '찾기/바꾸기'와 유사한 기능이라 생각하시면 이해하기 좋습니다.

 

replace함수는 파이썬에서 제공하는 모듈 '정규표현식(re)'와 함께 쓰면 더욱 강력합니다.

정규표현식이 궁금하신 분들은 아래 포스팅을 참고하면 좋습니다.

 

[Python] 데이터프레임을 엑셀 '찾기 및 바꾸기'처럼 쓰기 ; re함수

str.contains : 엑셀에서 'Ctrl + F'한 것과 동일하다 파이썬 re패키지 : 엑셀에서 '열'을 선택한 후 'Ctrl + F'한 후 '모두 바꾸기' 한 것과 동일한 결과이다. 예제파일 # 환경구축 import numpy as np impor..

bohemihan.tistory.com

 

 

 

1. 사용방법

 

문법

string.replace(oldvalue, newvalue, count)

 

매개변수

① oldvalue : Required

바꿀 값

② newvalue : Required

바꾼 값 (대체한 값)

③ count : Optional, int

바꾸는 횟수
>>> txt = "one two three, one two three, one two three"
>>> a = txt.replace("one", "two", 2)
>>> print(a)
two two three, two two three, one two three

 

 

 

2. 예제

 

2020년 서울 아파트 거래자료

2020_seoul_apt_trading.csv
5.27MB

 

(1) 데이터프레임을 불러옵니다.

import pandas as pd
import numpy as np

df = pd.read_csv('2020_seoul_apt_trading.csv', encoding='cp949')
df

 

(2) 데이터프레임의 정보를 확인합니다.

df.info()

거래금액은 object 타입입니다. 데이터분석을 용이하게 하기 위해 숫자형(int64)로 변형하겠습니다.

 

(3) astype을 써서 int로 변형합니다.

df['거래금액'] = df['거래금액'].astype('int64')

공백과 콤마가 있는 데이터가 있어서 숫자로 변형되지 않습니다.

따라서 공백과 콤마를 제거하기 위해 strip함수replace함수를 사용합니다.

 

(4) strip함수를 사용해서 공백을 제거합니다.

df['거래금액'] = df['거래금액'].str.strip()
df['거래금액'] = df['거래금액'].astype('int64')

공백이 제거됨을 확인할 수 있습니다.

 

(5) replace함수를 사용하여 콤마(,)를 제거한후 데이터타입을 변경합니다.

df['거래금액'] = df['거래금액'].str.replace(',', '')
df['거래금액'] = df['거래금액'].astype('int64')
df

콤마(,)도 제거되었고 데이터타입도 int64로 변경되었습니다.

 

 

 


 

 

 

판다스 replace 여러개, Pandas replace 사용법, 판다스 replace 조건, DataFrame 특정 위치 값 변경, Pandas 문자열 변환, Pandas 문자열 치환, 판다스 replace inplace, Pandas 값 대체, 파이썬 replace 특수문자, 파이썬 replace 특수문자 제거, 파이썬 replace 여러개, 파이썬 replaceAll, 파이썬 문자열 변경, 파이썬 replace 안됨, 파이썬 replace 인덱스, 파이썬 replace 리스트, 파이썬 replace 정규식, 파이썬 replace inplace, #판다스replace여러개 #Pandasreplace사용법 #판다스replace조건 #DataFrame특정위치값변경 #Pandas문자열변환 #Pandas문자열치환 #판다스replaceinplace #Pandas값대체 #파이썬replace특수문자 #파이썬replace특수문자제거 #파이썬replace여러개 #파이썬replaceAll #파이썬문자열변경 #파이썬replace안됨 #파이썬replace인덱스 #파이썬replace리스트 #파이썬replace정규식 #파이썬replaceinplace