GIL's LAB

ValueError: could not convert string to float 본문

파이썬/환경설정 및 오류 해결

ValueError: could not convert string to float

GIL~ 2025. 3. 4. 15:29

 

데이터 분석을 하다 보면 ValueError: could not convert string to float라는 에러를 만날 수 있습니다.

이 에러는 숫자로 변환할 수 없는 문자열이 포함된 경우 발생합니다.

예시를 보겠습니다

import numpy as np
arr = np.array(["1.23", "4.56", "hello", "7.89"])
arr = arr.astype(float)

 

[실행 결과]

ValueError: could not convert string to float: 'hello'

 

해결 방법은 간단합니다. 숫자로 변환할 수 없는 문자열은 숫자로 안바꾸는 것입니다.

다만 결측이 문자열로 표시된 경우가 있습니다. 

Kaggle에서 대표적인 문제인 Telco Churn Prediction(링크)에도 비슷한 경우가 있습니다.

TotalCharges란 컬럼이 그러한데, 이는 결측을 적당한 숫자로 바꿔주면 해결됩니다.

참고로 해당 컬럼이 결측인 이유는 실제 거래가 없어서이므로 0으로 대체해주면 됩니다.

즉, 다음과 같이 코드를 만들어줄 수 있습니다.

df['TotalCharges'] = df['TotalCharges'].replace({'':0}).astype(float)

 

 

Comments