Reputation: 89
i have problems rounding Decimals()
inside a Pandas Dataframe. The round()
method does not work and using quantize()
neither. I've searched for a solution with no luck so far.
round()
does nothing, i asume it is meant for float numbers
quantize()
won't work because it is not a DataFrame function
Any thoughts?
Upvotes: 3
Views: 1672
Reputation: 2456
Expanding a bit on the answer by @Juanito
With my data I got an InvalidOperation: [<class 'decimal.InvalidOperation'>]
This seems to be because my input data has more than the default precision of 28:
gdf_temp['latitude'][0]
Decimal('44.5001088968049742788934963755309581756591796875')
This worked:
getcontext().prec = 64
gdf_temp['longitude'] = gdf_temp['longitude'].apply(Decimal)
gdf_temp['latitude'] = gdf_temp['latitude'].apply(Decimal)
gdf_temp['longitude'] = gdf_temp['longitude'].apply((lambda x: x.quantize(Decimal('1.00000'))))
gdf_temp['latitude'] = gdf_temp['latitude'].apply((lambda x: x.quantize(Decimal('1.00000'))))
gdf_temp['latitude'][0]
Decimal('44.50011')
Upvotes: 1
Reputation: 127
To round your decimal to 2 significant figures for example:
round(df['yourSeries'].astype('float'), 2)
Or if you just want an int:
round(df['yourSeries'].astype('float'))
Upvotes: 0
Reputation: 89
Since pandas has no quantize method i used the following to solve the problem:
out.applymap(lambda x: x.quantize(dc.Decimal('1.00')))
Upvotes: 2