Pandas
[Pandas / 기초] 판다스 결측치 - isnull, notnull, isna, notna, fillna, dropna
씨주
2024. 1. 10. 16:10
📍 결측치
: 비어있는 데이터
✅ 엑셀로 열기
: pd.read_excel('파일명.xlsx', index_col='column')
In [1]:
import pandas as pd
df = pd.read_excel('score.xlsx', index_col='지원번호') # index 설정
df
Out[1]:

✅ 결측치로 채우기
: df['column'] = np.nan
In [2]:
import numpy as np
df['학교'] = np.nan # 학교 데이터 전체를 NaN으로 채움
df
Out[2]:
✅ 결측치 찾기
: isnull(), isna()
In [3]:
df['SW특기'].isnull()
Out[3]:
지원번호
1번 False
2번 False
3번 False
4번 True
5번 True
6번 False
7번 False
8번 False
Name: SW특기, dtype: bool
In [4]:
df['SW특기'].notnull()
Out[4]:
지원번호
1번 True
2번 True
3번 True
4번 False
5번 False
6번 True
7번 True
8번 True
Name: SW특기, dtype: bool
In [5]:
df['SW특기'].isna()
Out[5]:
지원번호
1번 False
2번 False
3번 False
4번 True
5번 True
6번 False
7번 False
8번 False
Name: SW특기, dtype: bool
In [6]:
df['SW특기'].notna()
Out[6]:
지원번호
1번 True
2번 True
3번 True
4번 False
5번 False
6번 True
7번 True
8번 True
Name: SW특기, dtype: bool
In [7]:
df[df['SW특기'].isnull()] # boolean indexing 적용 가능
Out[7]:

In [8]:
# 각 column 결측 데이터갯수
df.isna().sum()
Out[8]:
이름 0
학교 8
키 0
국어 0
영어 0
수학 0
과학 0
사회 0
SW특기 2
dtype: int64
In [9]:
# 전체 결측 데이터갯수
df.isnull().sum().sum()
Out[9]:
10
✅ 결측치 필터링
: df.loc[df['column'].isnull()]
In [10]:
# SW특기가 NaN인 값만 출력
df.loc[df['SW특기'].isnull()]
Out[10]:

✅ 결측치 대체
: df.fillna('data')
In [11]:
df = pd.read_excel('score.xlsx', index_col='지원번호')
df.fillna('') # NaN 데이터를 빈칸으로 채움
Out[11]:

In [12]:
df.fillna('없음', inplace=True)
df
Out[12]:

: 평균으로 대체
df['column'].fillna(df['column'].mean())
In [13]:
df.loc['2번', '국어'] = np.nan
df.loc['3번', '국어'] = np.nan
df['국어'].fillna(df['국어'].mean())
Out[13]:
지원번호
1번 90.000000
2번 63.333333
3번 63.333333
4번 40.000000
5번 15.000000
6번 80.000000
7번 55.000000
8번 100.000000
Name: 국어, dtype: float64
: 중앙값으로 대체
df['column'].fillna(df['column'].median())
In [14]:
df['국어'].fillna(df['국어'].median())
Out[14]:
지원번호
1번 90.0
2번 67.5
3번 67.5
4번 40.0
5번 15.0
6번 80.0
7번 55.0
8번 100.0
Name: 국어, dtype: float64
: 최빈값으로 대체
최빈값으로 채울 때는 [0]번째 index를 지정하여 채워야 함
df['column'].fillna(df['column'].mode()[0])
In [15]:
# 최빈값으로 채울 때는 [0]번째 index를 지정하여 채워야 함
df['국어'].fillna(df['국어'].mode()[0])
Out[15]:
지원번호
1번 90.0
2번 15.0
3번 15.0
4번 40.0
5번 15.0
6번 80.0
7번 55.0
8번 100.0
Name: 국어, dtype: float64
: 카테고리형 데이터 처리
- 이미 추가된 카테고리는 바로 fillna() 가능
- 없는 카테고리는 add_categories로 추가 후 가능
In [16]:
df = pd.read_excel('score.xlsx', index_col='지원번호')
df['SW특기'] = df['SW특기'].astype('category')
df['SW특기']
Out[16]:
지원번호
1번 Python
2번 Java
3번 Javascript
4번 NaN
5번 NaN
6번 C
7번 PYTHON
8번 C#
Name: SW특기, dtype: category
Categories (6, object): ['C', 'C#', 'Java', 'Javascript', 'PYTHON', 'Python']
In [17]:
df['SW특기'].cat.add_categories('No Data').fillna('No Data')
Out[17]:
지원번호
1번 Python
2번 Java
3번 Javascript
4번 No Data
5번 No Data
6번 C
7번 PYTHON
8번 C#
Name: SW특기, dtype: category
Categories (7, object): ['C', 'C#', 'Java', 'Javascript', 'PYTHON', 'Python', 'No Data']
✅ 결측치 제외
: df.dropna(axis, how)
- axis : index(default값) or columns
- how : any(default값) or all
In [18]:
df = pd.read_excel('score.xlsx', index_col='지원번호')
df.dropna(inplace=True)
df
Out[18]:

In [19]:
df = pd.read_excel('score.xlsx', index_col='지원번호')
# NaN이 하나라도 있는 row 삭제
df.dropna(axis='index', how='any')
Out[19]:

In [20]:
# NaN이 하나라도 있는 column 삭제
df.dropna(axis='columns')
Out[20]:

In [21]:
df['학교'] = np.nan
df
Out[21]:

In [22]:
# 데이터 전체가 NaN인 경우에만 column 삭제
df.dropna(axis='columns', how='all')
Out[22]:

참고 : 나도코딩 파이썬 코딩 무료 강의 (활용편5) - 데이터 분석 및 시각화, 이 영상 하나로 끝내세요