简体   繁体   English

Python3 pandas dataframe round.5 始终向上

[英]Python3 pandas dataframe round .5 always up

According to the documentation , Python rounds values toward the even choice if the upper and lower rounded values are equally close to the original number.根据文档,如果上舍入值和下舍入值同样接近原始数字,Python 会将值舍入到偶数选择。

I want to round values in my pandas.DataFrame such that 0.5 is always rounded up.我想对我的pandas.DataFrame中的值进行四舍五入,以使0.5始终向上舍入。

A way to fix it would be to use the decimal module with Decimal datatype as described here: How to properly round up half float numbers in Python?解决它的一种方法是使用具有Decimal数据类型的decimal模块,如下所述: 如何正确舍入 Python 中的半浮点数?

import pandas as pd

if __name__ == "__main__":
    df = pd.DataFrame(data=[0.5, 1.499999, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5], columns=["orig"])
    df["round"] = df.round()
    print(df)

which outputs:输出:

       orig  round
0  0.500000    0.0
1  1.499999    1.0
2  1.500000    2.0
3  2.500000    2.0
4  3.500000    4.0
5  4.500000    4.0
6  5.500000    6.0
7  6.500000    6.0

I tried to do something like:我试图做类似的事情:

df["round"] = df["orig"].values.astype(Decimal).round()

but this does not work.但这不起作用。 Is there a simple and readable solution to ensure that .5 is always rounded up?是否有一个简单易读的解决方案来确保.5总是四舍五入?

EDIT编辑

I'm not sure if the links in the comments answer the question.我不确定评论中的链接是否回答了这个问题。 The solution presented in the links is casting every float to a string and are manipulating the strings which seems ridiculous for large DataFrames.链接中提出的解决方案是将每个浮点数转换为一个字符串,并正在操作对于大型 DataFrame 来说似乎很荒谬的字符串。 (and is very hard to read/understand). (并且很难阅读/理解)。 I was hoping there is a simple function to use like in the decimal package我希望有一个简单的 function 可以像decimal package 一样使用

You can add some tiny value to orig when the decimal is 0.5 .当小数点为0.5时,您可以向orig添加一些微小的值。 That guarantees that any integer + 0.5 will always round up to the next integer.这保证了任何 integer + 0.5 将始终向上舍入到下一个 integer。

import numpy as np
df['round_up'] = np.round(np.where(df['orig'] % 1 == 0.5,
                                   df['orig'] + 0.1,
                                   df['orig']))
print(df)
       orig  round_up
0  0.500000       1.0
1  1.499999       2.0
2  1.500000       2.0
3  2.500000       3.0
4  3.500000       4.0
5  4.500000       5.0
6  5.500000       6.0
7  6.500000       7.0

Using the decimal module, you could do使用decimal模块,你可以做

import decimal
df = pd.DataFrame(data=[0.5, 1.499999, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5], columns=["orig"])

df.orig = df.orig.apply(
  lambda x: decimal.Decimal(x).to_integral_value(rounding=decimal.ROUND_HALF_UP)
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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