Decimal class rounding in Pandas

前端 未结 3 1008
小鲜肉
小鲜肉 2021-01-23 16:04

i have problems rounding Decimals() inside a Pandas Dataframe. The round() method does not work and using quantize() neither. I\'ve search

相关标签:
3条回答
  • 2021-01-23 16:18

    Since pandas has no quantize method i used the following to solve the problem:

    out.applymap(lambda x: x.quantize(dc.Decimal('1.00')))
    
    0 讨论(0)
  • 2021-01-23 16:28

    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'))

    0 讨论(0)
  • 2021-01-23 16:33

    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')

    0 讨论(0)
提交回复
热议问题