Pandas: inf를 최대 값으로 바꾸는 방법


다음 방법을 사용하여 inf-inf 값을 pandas DataFrame의 최대값으로 바꿀 수 있습니다.

방법 1: inf를 열의 최대값으로 바꾸기

 #find max value of column
max_value = np. nanmax (df[' my_column '][df[' my_column '] != np. inf ])

#replace inf and -inf in column with max value of column 
df[' my_column ']. replace ([np. inf , -np. inf ], max_value, inplace= True )

방법 2: inf를 모든 열의 최대값으로 바꾸기

 #find max value of entire data frame
max_value = np. nanmax (df[df != np.inf ])

#replace inf and -inf in all columns with max value
df. replace ([np. inf , -np. inf ], max_value, inplace= True )

다음 예는 다음 pandas DataFrame에서 실제로 이 구문을 사용하는 방법을 보여줍니다.

 import pandas as pd
import numpy as np

#createDataFrame
df = pd. DataFrame ({' points ': [18, np.inf, 19, np.inf, 14, 11, 20, 28],
                   ' assists ': [5, 7, 7, 9, 12, 9, 9, np.inf],
                   ' rebounds ': [np.inf, 8, 10, 6, 6, -np.inf, 9, 12]})

#view DataFrame
print (df)

   points assists rebounds
0 18.0 5.0 lower
1 lower 7.0 8.0
2 19.0 7.0 10.0
3 lower 9.0 6.0
4 14.0 12.0 6.0
5 11.0 9.0 -inf
6 20.0 9.0 9.0
7 28.0 lower 12.0

예 1: inf를 열의 최대값으로 바꾸기

다음 코드는 반송 열의 inf-inf 값을 반송 열의 최대값으로 바꾸는 방법을 보여줍니다.

 #find max value of rebounds
max_value = np. nanmax (df[' rebounds '][df[' rebounds '] != np. inf ])

#replace inf and -inf in rebounds with max value of rebounds
df[' rebounds ']. replace ([np. inf , -np. inf ], max_value, inplace= True )

#view updated DataFrame
print (df)

   points assists rebounds
0 18.0 5.0 12.0
1 lower 7.0 8.0
2 19.0 7.0 10.0
3 lower 9.0 6.0
4 14.0 12.0 6.0
5 11.0 9.0 12.0
6 20.0 9.0 9.0
7 28.0 lower 12.0

바운스 열의 각 inf-inf 값은 해당 열의 최대값인 12 로 대체되었습니다.

예 2: inf를 모든 열의 최대값으로 대체

다음 코드는 각 열의 inf-inf 값을 전체 데이터 프레임의 최대값으로 바꾸는 방법을 보여줍니다.

 #find max value of entire data frame
max_value = np. nanmax (df[df != np.inf ])

#replace all inf and -inf with max value
df. replace ([np. inf , -np. inf ], max_value, inplace= True )

#view updated DataFrame
print (df)

   points assists rebounds
0 18.0 5.0 28.0
1 28.0 7.0 8.0
2 19.0 7.0 10.0
3 28.0 9.0 6.0
4 14.0 12.0 6.0
5 11.0 9.0 28.0
6 20.0 9.0 9.0
7 28.0 28.0 12.0

각 열의 각 inf-inf 값은 전체 데이터 프레임의 최대값인 28 로 대체되었습니다.

추가 리소스

다음 튜토리얼에서는 Pandas에서 다른 일반적인 작업을 수행하는 방법을 설명합니다.

팬더에서 누락된 값을 대치하는 방법
팬더에서 누락된 값을 계산하는 방법
팬더에서 NaN 값을 평균으로 채우는 방법

의견을 추가하다

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