pd.DataFrame 사용시 NAN 주의

Junkyu_Kang·2024년 12월 2일

Pandas를 사용한다면 DataFrame을 사용할텐데

파이썬에서 NAN으로 넘겨보내면

프론트에서 Null로 인식하지 못한다.

        const replaceNaNWithNull = (obj) => {
            if (obj === null || obj === undefined) return obj;

            if (typeof obj === 'number' && isNaN(obj)) {
                return null;
            }

            if (Array.isArray(obj)) {
                return obj.map(replaceNaNWithNull);
            }

            if (typeof obj === 'object') {
                return Object.fromEntries(
                    Object.entries(obj).map(([key, value]) => [key, replaceNaNWithNull(value)])
                );
            }

            return obj;
        };

프론트에서 이런 식의 데이터 변환이 필요하다.

혹은 백엔드에서 하길 원한다면?
할 수 있다 당연히..

import json

def replace_nan_with_null(obj):
    if isinstance(obj, dict):
        return {k: replace_nan_with_null(v) for k, v in obj.items()}
    elif isinstance(obj, list):
        return [replace_nan_with_null(i) for i in obj]
    elif isinstance(obj, float) and (obj != obj):  # NaN을 체크하는 방법
        return None
    return obj

data = {
    "name": "junkyu",
    "age": float('nan'),
    "address": {
        "city": "Daejeon",
        "postalCode": float('nan')
    },
    "scores": [85, float('nan'), 92]
}

# NaN 처리
cleaned_data = replace_nan_with_null(data)
# JSON 응답으로 변환
json_data = json.dumps(cleaned_data)

print(json_data)

아니면 다른 방법도 있다.

import pandas as pd
import numpy as np

# 예시 DataFrame
data = {
    'name': ['Alice', 'Bob', 'Charlie', 'David'],
    'age': [25, np.nan, 30, np.nan],
    'score': [85, np.nan, 92, 88]
}
df = pd.DataFrame(data)

# NaN 값을 None으로 변환
df = df.where(pd.notnull(df), None)

print(df)

혹은

# NaN 값을 0으로 대체
df_filled = df.fillna(0)

# NaN 값을 -1로 대체
df_filled_negative = df.fillna(-1)

print(df_filled)

이런식으로 간단하게 가능하다.. 뻘짓하지말자..

프론트에서 계속 체크해야한다. type이 json이 아니라 String으로 나오고 resource.data 식으로 넘긴다 해도 NAN이 있다면 에러가 발생할 수 있다.

profile
강준규

0개의 댓글