본문 바로가기

짜투리

[pandas, null값 처리] 간특하고 악착스러운 null값 척결하기

728x90

 

 

 

 

  안녕하세요. 

 

 이번에는 파이썬에서 null값을 처리하는 방법에 대해 작성해보려고 합니다. 

 

  null값이라 말했지만 False, None, NaN, "" 등에 대해서 다룹니다. 

 

 


 

 테스트할 데이터는 다음과 같습니다. 

 

 

import numpy as np

test_df = pd.DataFrame({"data": ["False", False, "None", None, "", "NaN", np.nan, pd.NA]}) # 1,3,4,6,7

 

 

 

 

 여기서 제가 처리하고 싶은 데이터 idx는 1, 3, 4, 6, 7가 됩니다. 

 

for idx, row in test_df.iterrows():
    target = row['data']

    if pd.notnull(target):
        print(f"pd.notnull() {idx}")
    if pd.notna(target):
        print(f"pd.notna() {idx}")
    if pd.isnull(target):
        print(f"pd.isnull() {idx}")
    if pd.isna(target):
        print(f"pd.isna() {idx}")

 

 

 

 간단하게 표로 살펴봅시다. 보기 편하게 True인 경우만 표기하겠습니다.

 

번호 코드 0:"FALSE" 1:FALSE 2:"None" 3:None 4:"" 5:"NaN" 6:np.nan 7.pd.NA
1 pd.notnull() T T T   T T    
2 pd.notna() T T T   T T    
3 pd.isnull()       T     T T
4 ps.isna()       T     T T

 

 

 찾아보니까, pd.notnull()과 pd.notna(), pd.isnull()과 pd.isna() 설명이 똑같더라고요. ChatGPT가 둘이 똑같은 함수고, notna가 notnull이 alias라고 설명하길래 의심했는데. 맞나봐요. 

 

 

https://pandas.pydata.org/docs/reference/api/pandas.notnull.html

 

pandas.notnull — pandas 2.2.3 documentation

For scalar input, returns a scalar boolean. For array input, returns an array of boolean indicating whether each corresponding element is valid.

pandas.pydata.org

https://pandas.pydata.org/docs/reference/api/pandas.isnull.html

 

pandas.isnull — pandas 2.2.3 documentation

For scalar input, returns a scalar boolean. For array input, returns an array of boolean indicating whether each corresponding element is missing.

pandas.pydata.org

 

 

 그리고 어쩌면 당연하게도. notnull<->isnull 이에요. 설명이 아주 똑같습니다. 

 

 

 

 그럼 여기서 남는 건 False빈문자열입니다. 

 

for idx, row in test_df.iterrows():
    target = row['data']

    if target==False or pd.isnull(target) or target=="":
        print(idx)

 

 

 쨘. 사실 이건 완벽한 코드는 아닙니다. pd.NA의 경우 TypeError: boolean value of NA is ambiguous 에러가 발생합니다. 

 

 pd.NA의 경우, 모든 데이터 타입에서 결측치를 표시하기 위해 만들어졌대요. 

 

https://pandas.pydata.org/pandas-docs/version/1.0.0/whatsnew/v1.0.0.html#experimental-new-features

 

 

 구글링을 조금 해봤을 때. 위 코드 예시처럼, None값이 든 데이터프레임의 dtype을 정수형으로 변경할 때 등 특수한 상황에서 None이 <NA>로 바뀌는 것 같습니다.

 

 위와 같은 경우가 아니면, 보통은 pd.isnull()에서 걸러질 것 같다는 것이 저의 생각입니다.(아닐 수도 있습니다)

 


 

 작업 내용에 따라 위 코드도 바뀔 수 있을 것 같습니다. 예를 들어, 저는 word 데이터 중에 False가 있어서 이상 값이라고 생각했는데. 문장 내에 "False Positive"가 잘리면서 False(dtype=bool)가 들어간 경우도 있었습니다.

 

그 데이터는 아니지만 예시 코드

  

 

 또, 이전에 대량의 공공데이터를 다룰 때, pd.isnull()만 사용해서 null값을 처리하다가 큰코를 다친 적도 있었습니다. False와 공백 파티로 얼룩진 데이터는 정말이지 끔찍했습니다.

 

 

 무튼, 불현듯 생각 나서 짤막한 게시물 작성합니다. 

 

 감사합니다.