수정 방법: valueerror: float nan을 int로 변환할 수 없습니다.


pandas를 사용할 때 발생할 수 있는 오류는 다음과 같습니다.

 ValueError : cannot convert float NaN to integer

이 오류는 열에 NaN 값이 포함된 경우 Pandas DataFrame의 열을 부동 소수점에서 정수로 변환하려고 할 때 발생합니다.

다음 예에서는 실제로 이 오류를 수정하는 방법을 보여줍니다.

오류를 재현하는 방법

다음과 같은 pandas DataFrame을 생성한다고 가정합니다.

 import pandas as pd
import numpy as np

#createDataFrame
df = pd. DataFrame ({' points ': [25, 12, 15, 14, 19, 23, 25, 29],
                   ' assists ': [5, 7, 7, 9, 12, 9, 9, 4],
                   ' rebounds ': [11, np. no , 10, 6, 5, np. no , 9, 12]})

#view DataFrame
df

        points assists rebounds
0 25 5 11
1 12 7 NaN
2 15 7 10
3 14 9 6
4 19 12 5
5 23 9 NaN
6 25 9 9
7 29 4 12

현재 “bounces” 열은 “float” 데이터 유형입니다.

 #print data type of 'rebounds' column
df[' rebounds ']. dtype

dtype('float64')

“bounces” 열을 float에서 정수로 변환하려고 한다고 가정해 보겠습니다.

 #attempt to convert 'rebounds' column from float to integer
df[' rebounds '] = df[' rebounds ']. astype (int)

ValueError : cannot convert float NaN to integer 

“bounces” 열의 NaN 값을 정수 값으로 변환할 수 없기 때문에 ValueError 가 발생합니다.

오류를 수정하는 방법

이 오류를 해결하는 방법은 열을 부동 소수점에서 정수로 변환하기 전에 NaN 값을 처리하는 것입니다.

다음 코드를 사용하여 NaN 값이 포함된 행을 먼저 식별할 수 있습니다.

 #print rows in DataFrame that contain NaN in 'rebounds' column
print (df[df[' rebounds ']. isnull ()])

   points assists rebounds
1 12 7 NaN
5 23 9 NaN

그런 다음 열을 부동 소수점에서 정수로 변환하기 전에 NaN 값이 있는 행을 제거하거나 NaN 값을 다른 값으로 바꿀 수 있습니다.

방법 1: NaN 값이 있는 행 제거

 #drop all rows with NaN values
df = df. dropna ()

#convert 'rebounds' column from float to integer
df[' rebounds '] = df[' rebounds ']. astype (int) 

#view updated DataFrame
df
	points assists rebounds
0 25 5 11
2 15 7 10
3 14 9 6
4 19 12 5
6 25 9 9
7 29 4 12

#view class of 'rebounds' column
df[' rebounds ']. dtype

dtype('int64')

방법 2: NaN 값 바꾸기

 #replace all NaN values with zeros
df[' rebounds '] = df[' rebounds ']. fillna ( 0 )

#convert 'rebounds' column from float to integer
df[' rebounds '] = df[' rebounds ']. astype (int) 

#view updated DataFrame
df

	points assists rebounds
0 25 5 11
1 12 7 0
2 15 7 10
3 14 9 6
4 19 12 5
5 23 9 0
6 25 9 9
7 29 4 12

#view class of 'rebounds' column
df[' rebounds ']. dtype

dtype('int64')

두 가지 방법을 모두 사용하면 ValueError를 방지하고 부동 열을 정수 열로 성공적으로 변환할 수 있습니다.

추가 리소스

다음 튜토리얼에서는 Python의 다른 일반적인 오류를 수정하는 방법을 설명합니다.

수정방법: 열이 겹치는데 접미사가 지정되지 않음
수정 방법: ‘numpy.ndarray’ 개체에 ‘append’ 속성이 없습니다.
해결 방법: 모든 스칼라 값을 사용하는 경우 인덱스를 전달해야 합니다.

의견을 추가하다

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다