ValueError: Out of range float values are not JSON compliant

984 阅读1分钟

1 出现的背景: 使用pandas和django、djangorestframework在进行json和dataframe相互转换完成Response()返回数据出现上述错误

2 翻译后的意思: ValueError:超出范围的浮点值不符合JSON

3 我的解决方案: 将特殊字符替为nan 或者None

# 1 将原始的df的特殊符号转为nan
df.replace(to_replace=r'(^\s*$)|--', value=np.nan, regex=True, inplace=True)
# 2 将nan转None
df = df.where(df.notnull(), None)


# 备注:
# 也可以直接一步到位
df.replace(to_replace=r'(^\s*$)|--', value=None, regex=True, inplace=True)