Python, Pandas, Dataframe에서 NaN 값을 포함하는 열 찾기
isnull().any() 사용
isnull()
함수는 데이터프레임의 각 열에 NaN 값이 있는지 확인하고, any()
함수는 그 결과에서 True 값이 하나라도 있는지 확인합니다.
import pandas as pd
df = pd.DataFrame({'A': [1, 2, np.nan], 'B': [3, np.nan, 5], 'C': [6, 7, 8]})
# NaN 값을 포함하는 열 찾기
cols_with_nan = df.isnull().any()
# 결과 출력
print(cols_with_nan)
# 출력 결과
# A True
# B True
# C False
# dtype: bool
sum() 사용
sum()
함수는 NaN 값을 제외하고 값을 합산합니다. 따라서 각 열의 합이 0이면 해당 열에 NaN 값이 없는 것입니다.
# NaN 값을 포함하는 열 찾기
cols_with_nan = (df.sum(axis=0) == 0)
# 결과 출력
print(cols_with_nan)
# 출력 결과
# A False
# B True
# C False
# dtype: bool
describe() 사용
describe()
함수는 데이터프레임의 각 열에 대한 통계 정보를 제공합니다. 여기에는 NaN 값의 개수도 포함됩니다.
# NaN 값을 포함하는 열 찾기
cols_with_nan = df.describe().loc['count'] == 0
# 결과 출력
print(cols_with_nan)
# 출력 결과
# A False
# B True
# C False
# dtype: bool
반복문 사용
다음과 같이 반복문을 사용하여 NaN 값을 포함하는 열을 찾을 수도 있습니다.
# NaN 값을 포함하는 열 찾기
cols_with_nan = []
for col in df.columns:
if df[col].isnull().any():
cols_with_nan.append(col)
# 결과 출력
print(cols_with_nan)
# 출력 결과
# ['A', 'B']
참고 자료
import pandas as pd
import numpy as np
# 데이터프레임 생성
df = pd.DataFrame({'A': [1, 2, np.nan], 'B': [3, np.nan, 5], 'C': [6, 7, 8]})
# 방법 1: isnull().any() 사용
cols_with_nan_1 = df.isnull().any()
# 방법 2: sum() 사용
cols_with_nan_2 = (df.sum(axis=0) == 0)
# 방법 3: describe() 사용
cols_with_nan_3 = df.describe().loc['count'] == 0
# 방법 4: 반복문 사용
cols_with_nan_4 = []
for col in df.columns:
if df[col].isnull().any():
cols_with_nan_4.append(col)
# 결과 비교
print(cols_with_nan_1)
print(cols_with_nan_2)
print(cols_with_nan_3)
print(cols_with_nan_4)
A True
B True
C False
dtype: bool
A False
B True
C False
dtype: bool
A False
B True
C False
dtype: bool
['A', 'B']
NaN 값을 포함하는 열 찾는 대체 방법
loc 속성 사용
loc
속성을 사용하여 NaN 값을 포함하는 행과 열을 선택할 수 있습니다.
# NaN 값을 포함하는 행과 열 선택
df_with_nan = df.loc[df.isnull().any(axis=1), df.isnull().any(axis=0)]
# 결과 출력
print(df_with_nan)
# 출력 결과
# A B C
# 0 NaN 3 6
# 1 2 NaN 7
isin() 함수 사용
isin()
함수를 사용하여 특정 값 (예: NaN)을 포함하는 열을 선택할 수 있습니다.
# NaN 값을 포함하는 열 선택
cols_with_nan = df.columns[df.isin([np.nan]).any(axis=0)]
# 결과 출력
print(cols_with_nan)
# 출력 결과
# Index(['A', 'B'], dtype='object')
np.where() 함수 사용
np.where()
함수를 사용하여 NaN 값의 위치를 찾고, 해당 위치를 기반으로 열을 선택할 수 있습니다.
# NaN 값의 위치 찾기
nan_rows, nan_cols = np.where(np.isnan(df))
# NaN 값을 포함하는 열 선택
cols_with_nan = df.columns[np.unique(nan_cols)]
# 결과 출력
print(cols_with_nan)
# 출력 결과
# Index(['A', 'B'], dtype='object')
iterrows() 함수 사용
iterrows()
함수를 사용하여 데이터프레임의 각 행을 반복하고, NaN 값을 포함하는 열을 찾을 수 있습니다.
# NaN 값을 포함하는 열 찾기
cols_with_nan = []
for i, row in df.iterrows():
for col in df.columns:
if row[col] is np.nan:
cols_with_nan.append(col)
# 결과 출력
print(set(cols_with_nan))
# 출력 결과
# {'A', 'B'}
참고 자료
python pandas dataframe