Pandas: nan 값을 문자열로 바꾸는 방법


다음 방법을 사용하여 NaN 값을 Pandas DataFrame의 문자열로 바꿀 수 있습니다.

방법 1: DataFrame 전체에서 NaN 값을 문자열로 대체

 df. fillna ('', inplace= True )

방법 2: 특정 열의 NaN 값을 문자열로 대체

 df[[' col1 ', ' col2 ']] = df[[' col1 ', ' col2 ']]. fillna ('')

방법 3: NaN 값을 열의 문자열로 바꾸기

 df. col1 = df. col1 . fillna ('')

다음 예에서는 다음 Pandas DataFrame에서 각 메서드를 사용하는 방법을 보여줍니다.

 import pandas as pd
import numpy as np

#create DataFrame with some NaN values
df = pd. DataFrame ({' team ': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
                   ' points ': [np.nan, 11, 7, 7, 8, 6, 14, 15],
                   ' assists ': [5, np.nan, 7, 9, 12, 9, 9, 4],
                   ' rebounds ': [11, 8, 10, np.nan, 6, 5, 9, np.nan]})

#view DataFrame
df

team points assists rebounds
0 A NaN 5.0 11.0
1 A 11.0 NaN 8.0
2 A 7.0 7.0 10.0
3 A 7.0 9.0 NaN
4 B 8.0 12.0 6.0
5 B 6.0 9.0 5.0
6 B 14.0 9.0 9.0
7 B 15.0 4.0 NaN

방법 1: DataFrame 전체에서 NaN 값을 문자열로 대체

다음 코드는 전체 DataFrame의 각 NaN 값을 빈 문자열로 바꾸는 방법을 보여줍니다.

 #replace NaN values in all columns with empty string
df. fillna ('', inplace= True )

#view updated DataFrame
df

	team points assists rebounds
0 A 5.0 11.0
1 A 11.0 8.0
2 A 7.0 7.0 10.0
3 A 7.0 9.0	
4 B 8.0 12.0 6.0
5 B 6.0 9.0 5.0
6 B 14.0 9.0 9.0
7B 15.0 4.0	

각 열의 각 NaN 값은 빈 문자열로 대체되었습니다.

방법 2: 특정 열의 NaN 값을 문자열로 대체

다음 코드는 특정 열의 NaN 값을 특정 문자열로 바꾸는 방법을 보여줍니다.

 #replace NaN values in 'points' and 'rebounds' columns with 'none'
df[[' points ', ' rebounds ']] = df[[' points ', ' rebounds ']]. fillna (' none ')

#view updated DataFrame
df

        team points assists rebounds
0 A none 5.0 11.0
1 A 11.0 NaN 8.0
2 A 7.0 7.0 10.0
3 A 7.0 9.0 none
4 B 8.0 12.0 6.0
5 B 6.0 9.0 5.0
6 B 14.0 9.0 9.0
7 B 15.0 4.0 none	

“포인트” 및 “리바운드” 열의 NaN 값은 “none” 문자열로 대체되었지만 “어시스트” 열의 NaN 값은 변경되지 않았습니다.

방법 3: NaN 값을 열의 문자열로 바꾸기

다음 코드는 열의 NaN 값을 특정 문자열로 바꾸는 방법을 보여줍니다.

 #replace NaN values in 'points' column with 'zero'
df. points = df. points . fillna (' zero ')

#view updated DataFrame
df

	team points assists rebounds
0 To zero 5.0 11.0
1 A 11.0 NaN 8.0
2 A 7.0 7.0 10.0
3 A 7.0 9.0 NaN
4 B 8.0 12.0 6.0
5 B 6.0 9.0 5.0
6 B 14.0 9.0 9.0
7 B 15.0 4.0 NaN	

“포인트” 열의 NaN 값은 문자열 “0”으로 대체되었지만 “어시스트” 및 “리바운드” 열의 NaN 값은 변경되지 않은 채 유지되었습니다.

추가 리소스

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

Pandas: 조건에 따라 열의 값을 바꾸는 방법
Pandas: NaN 값을 0으로 바꾸는 방법
Pandas: DataFrame에서 누락된 값을 계산하는 방법

의견을 추가하다

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