차례
1. 사용방법
2. 예제
파이썬이 제공하는 replace 함수는 '바꾸는' 기능이 있습니다.
엑셀의 '찾기/바꾸기'와 유사한 기능이라 생각하시면 이해하기 좋습니다.
replace함수는 파이썬에서 제공하는 모듈 '정규표현식(re)'와 함께 쓰면 더욱 강력합니다.
정규표현식이 궁금하신 분들은 아래 포스팅을 참고하면 좋습니다.
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년 서울 아파트 거래자료
(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
'Develop > Python' 카테고리의 다른 글
[Python] 압축파일(zipfile) 쉽게 읽기, 해제하기, 압축하기 (0) | 2022.09.23 |
---|---|
[Python] 데이터프레임에서 공백 쉽게 제거하는 방법 (str.strip) (0) | 2022.09.21 |
[Python] 요일 구하기 (datetime) (0) | 2022.06.18 |
[Python] 반올림, 올림, 내림, 소수점 버림 (round, ceil, floor, trunc) (0) | 2022.06.18 |
[Python] 나누기, 몫, 나머지 ( / , // , % , divmod ) (0) | 2022.06.18 |