Pandas fillna()를 사용하여 nan 값을 바꾸는 방법


fillna() 함수를 사용하여 Pandas DataFrame의 NaN 값을 바꿀 수 있습니다.

이 함수는 다음 기본 구문을 사용합니다.

 #replace NaN values in one column
df[' col1 '] = df[' col1 ']. fillna (0)

#replace NaN values in multiple columns
df[[' col1 ', ' col2 ']] = df[[' col1 ', ' col2 ']]. fillna (0) 

#replace NaN values in all columns
df = df. fillna (0)

이 튜토리얼에서는 다음 pandas DataFrame에서 이 함수를 사용하는 방법을 설명합니다.

 import numpy as np
import pandas as pd

#create DataFrame with some NaN values
df = pd.DataFrame({'rating': [np.nan, 85, np.nan, 88, 94, 90, 76, 75, 87, 86],
                   'points': [25, np.nan, 14, 16, 27, 20, 12, 15, 14, 19],
                   'assists': [5, 7, 7, np.nan, 5, 7, 6, 9, 9, 5],
                   'rebounds': [11, 8, 10, 6, 6, 9, 6, 10, 10, 7]})

#view DataFrame
df

        rating points assists rebounds
0 NaN 25.0 5.0 11
1 85.0 NaN 7.0 8
2 NaN 14.0 7.0 10
3 88.0 16.0 NaN 6
4 94.0 27.0 5.0 6
5 90.0 20.0 7.0 9
6 76.0 12.0 6.0 6
7 75.0 15.0 9.0 10
8 87.0 14.0 9.0 10
9 86.0 19.0 5.0 7

예시 1: 열의 NaN 값 바꾸기

다음 코드는 “note” 열에서 NaN 값을 0으로 바꾸는 방법을 보여줍니다.

 #replace NaNs with zeros in 'rating' column
df[' rating '] = df[' rating ']. fillna (0)

#view DataFrame
df

	rating points assists rebounds
0 0.0 25.0 5.0 11
1 85.0 NaN 7.0 8
2 0.0 14.0 7.0 10
3 88.0 16.0 NaN 6
4 94.0 27.0 5.0 6
5 90.0 20.0 7.0 9
6 76.0 12.0 6.0 6
7 75.0 15.0 9.0 10
8 87.0 14.0 9.0 10
9 86.0 19.0 5.0 7

예시 2: 여러 열의 NaN 값 바꾸기

다음 코드는 “등급” 및 “점수” 열에서 NaN 값을 0으로 바꾸는 방법을 보여줍니다.

 #replace NaNs with zeros in 'rating' and 'points' columns
df[[' rating ', ' points ']] = df[[' rating ', ' points ']]. fillna (0)

#view DataFrame
df

	rating points assists rebounds
0 0.0 25.0 5.0 11
1 85.0 0.0 7.0 8
2 0.0 14.0 7.0 10
3 88.0 16.0 NaN 6
4 94.0 27.0 5.0 6
5 90.0 20.0 7.0 9
6 76.0 12.0 6.0 6
7 75.0 15.0 9.0 10
8 87.0 14.0 9.0 10
9 86.0 19.0 5.0 7

예시 3: 모든 열의 NaN 값 바꾸기

다음 코드는 각 열의 NaN 값을 0으로 바꾸는 방법을 보여줍니다.

 #replace NaNs with zeros in all columns 
df = df. fillna (0)

#view DataFrame
df

        rating points assists rebounds
0 0.0 25.0 5.0 11
1 85.0 0.0 7.0 8
2 0.0 14.0 7.0 10
3 88.0 16.0 0.0 6
4 94.0 27.0 5.0 6
5 90.0 20.0 7.0 9
6 76.0 12.0 6.0 6
7 75.0 15.0 9.0 10
8 87.0 14.0 9.0 10
9 86.0 19.0 5.0 7

fillna() 함수에 대한 전체 온라인 설명서는 여기에서 찾을 수 있습니다.

추가 리소스

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

팬더에서 누락된 값을 계산하는 방법
Pandas에서 NaN 값이 있는 행을 삭제하는 방법
Pandas에서 특정 값이 포함된 행을 삭제하는 방법

의견을 추가하다

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