[英]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.我想使用 function 将 dataframe 中的列四舍五入到 x 个位置,以确保 any.5 值始终按照常规四舍五入规则四舍五入,并避免“银行家四舍五入”问题。
The dataframe sample I have is:我拥有的 dataframe 样品是:
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: dataframe 的数据类型为:
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).
(当然 dataframe 要大得多,因此我需要在列上工作)。
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: 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.您正在执行将
series
作为参数传递的舍入操作。 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:我建议你在
lambda
中使用map
和 lambda 来做到这一点:
Data['Numerator'] = Data['Numerator'].map(lambda x: Decimal(x).quantize(Decimal('.1'), rounding=ROUND_HALF_UP))
The output we get is as expected:我们得到的output和预期的一样:
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().
在应用 Decimal() 之前尝试将浮点数转换为文本。 You will get the result of ROUND_HALF_UP.
您将得到 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.这就是我结束的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.