简体   繁体   中英

Python round half up on dataframe question

Good afternoon,

I would like to round columns in a dataframe to x number of places using the round half up function to ensure that any.5 values are always rounded up as per conventional rounding rules and to avoid the "bankers rounding" issue.

The dataframe sample I have is:

import pandas as pd
import decimal

Data = {'Code' : ['x', 'x', 'x'],
        'Disaggregation' : ['a', 'b', 'Total'],
        'Numerator' : [19.3276542, 82.136492834, 101.192747123]}
       
Data = pd.DataFrame(Data, columns = ['Code', 'Disaggregation', 'Numerator'])

The code I have got, which does not work is as follow:

Data['Numerator'] = (Decimal(Data['Numerator']).quantize(Decimal('.1'), rounding=ROUND_HALF_UP))

The following error is produced: conversion from Series to Decimal is not supported.

Dtypes of the dataframe is:

Code               object
Disaggregation     object
Numerator         float64
dtype: object

Anyone have any clues how I can get this to work? (Of course the dataframe is much larger, thus I need to work on the column).

Thanks very much for this help on this in advance.

try:

Data['Numerator'] = Data.Numerator.apply(lambda x : round(x, 1))

change the number to your desired rounding value

output:

Code    Disaggregation  Numerator
0   x   a               19.3
1   x   b               82.1
2   x   Total           101.2

You are performing the rounding operation passing a series as an argument. Instead you need to fix this to perform the rounding up for each value in the series. I suggest you use map with a lambda in the function to do it:

Data['Numerator'] = Data['Numerator'].map(lambda x: Decimal(x).quantize(Decimal('.1'), rounding=ROUND_HALF_UP))

The output we get is as expected:

  Code Disaggregation Numerator
0    x              a      19.3
1    x              b      82.1
2    x          Total     101.2

Late for the party. Try to convert your float numbers to text before applying the Decimal(). You will get the result of ROUND_HALF_UP.

import pandas as pd
from decimal import Decimal, ROUND_HALF_UP

Data = {'Code' : ['x', 'x', 'x'],
        'Disaggregation' : ['a', 'b', 'Total'],
        'Numerator' : [19.3276, 82.1365, 101.1927]}

Data = pd.DataFrame(Data, columns = ['Code', 'Disaggregation', 'Numerator'])
Data['Numerator'].map(lambda x: Decimal(str(x)).quantize(Decimal('.100'), rounding=ROUND_HALF_UP))

This is what I ended with.

  • 19.328
  • 82.137
  • 101.193

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM