[Pandas] replace / astype
Pandas replace / astype, Pandas replace, Pandas astype, 값 치환 pandas, dtype 변환
정의
replace(...): 특정 값을 다른 값으로 치환astype(...): dtype 변환
replace 기본
s.replace('A', 'X') # 단일 값
s.replace(['A', 'B'], 'X') # 여러 값을 하나로
s.replace(['A', 'B'], ['X', 'Y']) # 매핑
s.replace({'A': 'X', 'B': 'Y'}) # dict 매핑
python
import pandas as pd
s = pd.Series(['A', 'B', 'C', 'A', 'B'])
print(s.replace({'A': 1, 'B': 2, 'C': 3}).tolist()) 결과
[1, 2, 3, 1, 2]정규식
s.replace(r'^\s+', '', regex=True) # 앞 공백 제거
s.replace({r'\d+': 'NUM'}, regex=True) # 숫자 → 'NUM'
IMPORTANT
pandas 2.0+ 에서 replace 의 regex 기본값이 False. 정규식 쓰려면 regex=True 명시.
DataFrame.replace
df.replace('?', pd.NA) # 모든 셀
df.replace({'A': {'old': 'new'}}) # 컬럼별 매핑
df.replace({'name': 'unknown', 'city': 'N/A'}, pd.NA)
NaN 으로 치환
df.replace('', pd.NA)
df.replace(['', '?', '-', 'N/A'], pd.NA)
# [[Pandas dropna / fillna]] 와 조합
str.replace 와의 차이
Series.replace: 전체 값 매칭 (정확히 일치)Series.str.replace: 부분 문자열 매칭
s = pd.Series(['hello world', 'world cup'])
s.replace('world', 'X') # 그대로 (전체 일치 안 함)
s.str.replace('world', 'X') # 'hello X', 'X cup'
astype 기본
df['age'] = df['age'].astype('int32')
df['code'] = df['code'].astype(str)
df['city'] = df['city'].astype('category')
df['flag'] = df['flag'].astype(bool)
여러 컬럼 한 번에
df = df.astype({
'id': 'int32',
'name': 'string[pyarrow]',
'age': 'Int8',
'is_active': 'boolean',
})
자주 쓰는 dtype
| dtype | 의미 |
|---|---|
int8, int16, int32, int64 | 정수 (NaN 미허용) |
Int8, Int16, Int32, Int64 | nullable 정수 (NaN 허용) |
float32, float64 | 실수 |
bool | True/False |
boolean | nullable bool |
object | 임의 Python 객체 (보통 str) |
string[pyarrow] | pyarrow 문자열 (효율적) |
category | 카테고리 |
datetime64[ns] | 날짜 |
timedelta64[ns] | 시간 차이 |
변환 함정 (errors)
df['x'].astype('int64') # 변환 실패 시 ValueError
pd.to_numeric(df['x'], errors='coerce') # 실패 시 NaN
pd.to_numeric(df['x'], errors='ignore') # 원본 반환
to_numeric, to_datetime, to_timedelta 에는 errors 옵션이 있다.
astype vs to_numeric / to_datetime
# 같은 결과지만 처리 방식 다름
df['x'].astype('int64') # 엄격, 실패 시 throw
pd.to_numeric(df['x'], errors='coerce') # 관대, 실패 → NaN
데이터 클리닝에는 to_numeric / to_datetime 권장.
자주 쓰는 패턴
category 로 메모리 절약
df['city'] = df['city'].astype('category')
df.memory_usage(deep=True)
NaN-aware 정수
df['count'] = df['count'].astype('Int64') # NaN 가능 정수
bool → 0/1
df['flag_int'] = df['flag'].astype(int)
정수 → 문자 (zfill)
df['code_str'] = df['code'].astype(str).str.zfill(8)
# 12345 → '00012345'
함정
1. NaN 이 있는 int 컬럼
df['age'].astype('int64') # NaN 있으면 ValueError
df['age'].astype('Int64') # ✓ nullable
df['age'].fillna(0).astype('int64') # NaN → 0 후 변환
2. astype(‘category’) 후 새 카테고리 추가
df['city'] = df['city'].astype('category')
df.loc[100, 'city'] = 'NewCity' # ❌ categories 에 없음
df['city'] = df['city'].cat.add_categories('NewCity')
3. dtype 강등 (object)
df['x'] = df['x'].where(cond, 'fallback')
# x 가 int 였어도 결과는 object
참고
이 글의 용어 (3개)
- [Pandas] Categoricalpandas
- 정의 Categorical 은 제한된 고유값 만 가질 수 있는 dtype. 내부적으로 정수 코드로 저장되어 메모리 절약 과 속도 향상. 사용 <CodeWithOutput lang…
- [Pandas] dropna / fillnapandas
- 정의 - : NaN 이 있는 행/열 제거 - : NaN 을 특정 값으로 대체 데이터 분석의 가장 기본적인 결측치 처리. dropna 기본 <CodeWithOutput langua…
- [Pandas] to_datetimepandas
- 정의 는 문자열/숫자를 datetime 으로 변환. pandas 의 시계열 작업의 시작. 기본 <CodeWithOutput language="python" outputLangua…
💬 댓글