python - ast.literal_eval() method truncates float value while converting str to dict -
here trying convert dict string using ast
module. found values truncated shown in output below. how can atual value without truncation here.
code
df = dataframe({ 'a': np.random.randn(6), 'b':['foo','bar']*3, 'c':np.random.randn(6) }) mapping = df.to_dict() d=str(mapping) e= ast.literal_eval(d) print mapping print;print e
output
{'a': {0: 0.88241526852727104, 1: -0.062779346232699929, 2: -0.058427377402568821, 3: 0.87157579927705897, 4: -1.0399255501591143, 5: 0.11203584043469664}, 'c': {0: 0.56763771194925394, 1: 0.22824054879261255, 2: -0.58324477854217549, 3: -0.2264734421572463, 4: 0.45754374820401839, 5: 1.35849692636584}, 'b': {0: 'foo', 1: 'bar', 2: 'foo', 3: 'bar', 4: 'foo', 5: 'bar'}}
`
{'a': {0: 0.882415268527271, 1: -0.06277934623269993, 2: -0.05842737740256882, 3: 0.871575799277059, 4: -1.0399255501591143, 5: 0.11203584043469664}, 'c': {0: 0.5676377119492539, 1: 0.22824054879261255, 2: -0.5832447785421755, 3: -0.2264734421572463, 4: 0.4575437482040184, 5: 1.35849692636584}, 'b': {0: 'foo', 1: 'bar', 2: 'foo', 3: 'bar', 4: 'foo', 5: 'bar'}}
the difference type, not value. numpy.float64
uses more precision needed represent float on printing, , represents exactly. python's float
type gives precision needed have value round correctly on conversion float.
if want original dictionary, you'll have convert floats numpy.float64
s.
type(dataframe({0: [0.88241526852727104]}).to_dict()[0][0]) #>>> <class 'numpy.float64'>
float64(0.882415268527271) #>>> 0.88241526852727104 float64(0.88241526852727104) #>>> 0.88241526852727104 0.88241526852727104 #>>> 0.882415268527271 float64(0.88241526852727104) == 0.88241526852727104 #>>> true float(float64(0.88241526852727104)) == 0.88241526852727104 #>>> true
Comments
Post a Comment