Am使用以下功能:
def round_half_away_from_zero(n, decimals=1):
rounded_abs = round_half_up(abs(n), decimals)
return math.copysign(rounded_abs, n)
def round_half_up(n, decimals=1):
multiplier = 10 ** decimals
return math.floor(n*multiplier + 0.5) / multiplier
def round_half_down(n, decimals=1):
multiplier = 10 ** decimals
return math.ceil(n*multiplier - 0.5) / multiplier
df['temp'] = df3['temp'].apply(lambda x: round_half_away_from_zero(x))
他浮动然后更新,除三项外,整个列的行为均应假定为: 例如:
奇怪的是,只有三个条目无效,它们是:
如果我只是对单个值执行函数,则可以,但不能在序列中使用,例如:
round_half_away_from_zero(67.5)
它有效,分别给出67.8、58.3和46.7。
任何想法,谢谢
答案 0 :(得分:0)
您的代码有效-无法复制您的错误:
import pandas as pd
import math
def round_half_away_from_zero(n, decimals=1): rounded_abs = round_half_up(abs(n), decimals) return math.copysign(rounded_abs, n) def round_half_up(n, decimals=1): multiplier = 10 ** decimals return math.floor(n*multiplier + 0.5) / multiplier
df = pd.DataFrame( {"A": [63.5, 58.355, 88.878, 48.75] ,
"B": [67.75, 58.25, 46.65, 67.75] })
df['A_ok'] = df['A'].apply(lambda x: round_half_away_from_zero(x))
df['B_ok'] = df['B'].apply(lambda x: round_half_away_from_zero(x))
print(df)
输出:
# python 2.7
A B A_ok B_ok
0 63.500 67.75 63.5 67.8
1 58.355 58.25 58.4 58.3
2 88.878 46.65 88.9 46.7
3 48.750 67.75 48.8 67.8
# python 3.6
A B A_ok B_ok
0 63.500 67.75 63.5 67.8
1 58.355 58.25 58.4 58.3
2 88.878 46.65 88.9 46.7
3 48.750 67.75 48.8 67.8
答案 1 :(得分:0)
回到这个问题,我发现当小数乘以100时,我遇到的三个数字都存在问题,四舍五入-这是一个浮点问题,我通过四舍五入后转换为十进制包来解决了这个问题< / p>