데이터프레임 값에 NaN이 있는지 확인하기
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
How to check if any value is NaN in a Pandas DataFrame
판다스 데이터프레임에서 값이 NaN인지 확인하는 방법
문제 내용
In Python Pandas, what's the best way to check whether a DataFrame has one (or more) NaN values?
파이썬 판다스에서 데이터프레임에 하나 이상의 NaN 값이 있는지 확인하는 가장 좋은 방법은 무엇입니까?
I know about the function pd.isnan
, but this returns a DataFrame of booleans for each element. This post right here doesn't exactly answer my question either.
pd.isnan 함수에 대해 알고 있지만 이것은 각 요소에 대한 부울의 DataFrame을 반환합니다. 여기 이 게시물도 내 질문에 정확히 대답하지 않습니다.
높은 점수를 받은 Solution
jwilner's response is spot on. I was exploring to see if there's a faster option, since in my experience, summing flat arrays is (strangely) faster than counting. This code seems faster:
jwilner의 답변이 정확합니다. 제 경험상 평면 배열을 합산하는 것이 계산하는 것보다 (이상하게도) 빠르기 때문에 더 빠른 옵션이 있는지 알아보고 있었습니다. 이 코드는 더 빨라 보입니다
df.isnull().values.any()
import numpy as np
import pandas as pd
import perfplot
def setup(n):
df = pd.DataFrame(np.random.randn(n))
df[df > 0.9] = np.nan
return df
def isnull_any(df):
return df.isnull().any()
def isnull_values_sum(df):
return df.isnull().values.sum() > 0
def isnull_sum(df):
return df.isnull().sum() > 0
def isnull_values_any(df):
return df.isnull().values.any()
perfplot.save(
"out.png",
setup=setup,
kernels=[isnull_any, isnull_values_sum, isnull_sum, isnull_values_any],
n_range=[2 ** k for k in range(25)],
)
df.isnull().sum().sum()
is a bit slower, but of course, has additional information -- the number of NaNs
.
df.isnull().sum().sum()은 약간 느리지만 물론 NaN의 수와 같은 추가 정보가 있습니다.
가장 최근 달린 Solution
This will only include columns with at least 1 null/na value.
여기에는 null/na 값이 하나 이상인 열만 포함됩니다.
df.isnull().sum()[df.isnull().sum()>0]
출처 : https://stackoverflow.com/questions/29530232/how-to-check-if-any-value-is-nan-in-a-pandas-dataframe