Py学习  »  Python

python round不返回整数

paradoxlover • 7 年前 • 2126 次点击  

我编写了以下代码以舍入数据帧中的浮动值 a

a = pd.DataFrame([[1.2,3.4],[1.4,4.6]])
a = a.apply(round)

但我得到的结果如下:

    0   1
0   1.0 3.0
1   1.0 5.0

为什么函数返回的是四舍五入的浮点值而不是整数?

此外,在按如下方式应用时,其行为也不同:

round(0.5)
>>0
x= [1.4,2.5,3.6]
list(map(round,x))

>>[1, 2, 4]

为什么会出现这种异常?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/44296
文章 [ 2 ]  |  最新文章 7 年前
pyeR_biz
Reply   •   1 楼
pyeR_biz    7 年前
a = a.apply(round).astype(dtype=np.int64)

就用这个 astype 转换您的 float 到 integer .

cs95
Reply   •   2 楼
cs95    7 年前

apply 调用 round 在每个列上连续运行。数据框列是 Series 对象,以及 these have a __round__ dunder method defined on them 行为稍有不同。实际上这就是 圆 打电话给 系列 .

round(a[0])

0    1.0
1    1.0
Name: 0, dtype: float64

# Same as,
a[0].__round__()

0    1.0
1    1.0
Name: 0, dtype: float64

与python的典型行为相比 圆 标量:

round(1.5)
# 2

 # Same as,
(1.5).__round__()
# 2

如果你想要同样的行为,使用 applymap .

a.applymap(round)

   0  1
0  1  3
1  1  5

适用于 圆 在每一个 要素 (标量),舍入为整数。

或者,我推荐的解决方案,

a.round().astype(int)

   0  1
0  1  3
1  1  5

请注意,这不会对包含丢失数据(nan)的列进行类型转换。