I have a data-class
from dataclasses import dataclass
@dataclass
class ModelResult:
scorecard_calcs: dict
This one is then used in the Model class
import pandas as pd
import numpy as np
class Model:
def predict(self, input):
scorecard_calcs = pd.DataFrame([{'val':np.inf}, {'val':-np.inf}]).to_dict()
return ModelResult(scorecard_calcs=scorecard_calcs)
Somewhere else this will be converted into json, but inf
is not valid json.
How can I change the ModelResult
dataclass, so it automatically replaces all inf values with 1.7976931348623157e+308
which is valid json.
Here is how I did it with a __post_init__
as suggested by @balderman
from dataclasses import dataclass
import numpy as np
ALMOST_INF = 1.7976931348623157e308
@dataclass
class ModelResult:
scorecard_calcs: dict
pd: float
@staticmethod
def replace_inf(val):
if not isinstance(val, (int, float, complex)):
return val
if np.isposinf(val):
return ALMOST_INF
if np.isneginf(val):
return -ALMOST_INF
return val
def __post_init__(self):
self.pd = self.replace_inf(self.pd)
scorecard_calcs = pd.DataFrame(self.scorecard_calcs)
scorecard_calcs = scorecard_calcs.applymap(self.replace_inf)
self.scorecard_calcs = scorecard_calcs.to_dict()
This works, since I know for a fact that scorecard_calcs is a dict which was previously a pandas data-frame.