언빌리버블티
[Python] Pandas data type을 숫자로 변환하기 - pd.to_numeric() 본문
Pandas 데이터를 숫자 형식으로 변환하기
pd.to_numeric()
- 숫자형식으로 변경시킬 대상으로 스칼라값, list, tuple, Series 등을 지정
pandas.to_numeric(arg, errors='raise', downcast=None)
errors 파라미터
' ignore ' : 만약 숫자로 변경할 수 없는 데이터라면 숫자로 변경하지 않고 원본 데이터를 그대로 반환
' coerce ' : 만약 숫자로 변경할 수 없는 데이터라면 기존 데이터를 지우고 NaN으로 설정하여 반환
' raise ' : 만약 숫자로 변경할 수 없는 데이터라면 에러 발생 후 코드 중단
downcast 파라미터
INT8 , Float32 형식 등을 지정해줄 수 있다 .
활용 예시
문자형인 숫자와 숫자가 섞인 경우
import pandas as pd
series = pd.Series( ['1', 2, '3'])
0 1
1 2
2 3
dtype: object
<class 'pandas.core.series.Series'>
- 1과 3이 문자인 시리즈 데이터를 int 자료형으로 바꾸기 위해 pd.to_numeric() 을 사용한다.
pd.to_numeric(series)
0 1
1 2
2 3
dtype: int64
<class 'pandas.core.series.Series'>
숫자로 변환할 수 없는 문자가 들어있는 경우
1) error 인자를 ignore로 설정하면 숫자로 바꿀 수 없는 경우 건너뛴다.
import pandas as pd
series = pd.Series( ['1' ,'test' ,3 ])
pd.to_numeric(series, errors='ignore')
0 1
1 test
2 3
dtype: object
<class 'pandas.core.series.Series'>
2) error 인자를 coerce로 설정하면 숫자로 바꿀 수 없는 경우 NaN값으로 채운다.
import pandas as pd
series = pd.Series( ['1' ,'test' ,3 ])
pd.to_numeric(series, errors='coerce')
0 1.0
1 NaN
2 3.0
dtype: float64
<class 'pandas.core.series.Series'>
3) error 인자를 raise로 설정하면 숫자로 바꿀 수 없을 때 에러를 발생하고 코드를 종료시킨다.
import pandas as pd
series = pd.Series( ['1' ,'test' ,3 ])
pd.to_numeric(series, errors='raise')
ValueError: Unable to parse string "test" at position 1
<class 'pandas.core.series.Series'>
Reference
pandas.to_numeric — pandas 1.5.0 documentation
Can be ‘integer’, ‘signed’, ‘unsigned’, or ‘float’. If not None, and if the data has been successfully cast to a numerical dtype (or if the data was numeric to begin with), downcast that resulting data to the smallest numerical dtype possib
pandas.pydata.org
Python Pandas : pandas.to_numeric (data type을 숫자로 바꾸기)
pandas.to_numeric to_numeric은 데이터를 숫자 형식으로 바꿔주는 역할을 합니다. to_numeric의 대표적 인자는 아래와 같습니다. pd.to_numeric(숫자로 변경할 대상, errors='ignore/raise/coerce') 숫자로 변경..
cosmosproject.tistory.com
'Language > Python' 카테고리의 다른 글
[Python] Pandas 시리즈 접근자 ( dt. str. cat. sparse. ) (0) | 2022.10.12 |
---|---|
[Python] Pandas List를 이용한 요소 필터링 - pd.isin() (0) | 2022.10.12 |
[Python] Pandas 데이터프레임 조건 탐색 및 대치 메서드 pd.where 과 np.where 차이 (0) | 2022.10.11 |
[Python] Pandas Dataframe 누적합과 누적곱 구하기 - pd.cumsum() / pd.cumprod() (0) | 2022.10.11 |
[Python] Pandas 데이터 프레임 병합 메서드 - pd.merge() (0) | 2022.10.07 |
Comments