Python round不返回整数



我编写了以下代码段来舍入数据帧中的浮点值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]

为什么会出现这种异常?

apply连续调用每列上的round函数。数据帧列是Series对象,这些列在其上定义了 __round__ dunder 方法,其行为略有不同。这实际上是roundSeries上调用时所说的。

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的典型行为进行对比:

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

如果需要相同的行为,请使用 applymap

a.applymap(round)
   0  1
0  1  3
1  1  5

它适用于每个元素(标量(的round,向下舍入为整数。

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

a.round().astype(int)
   0  1
0  1  3
1  1  5

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

a = a.apply(round).astype(dtype=np.int64)

只需使用此astype即可将您的float转换为integer

最新更新