Python round 不返回整数

par*_*ver 4 python python-3.x pandas

我编写了以下代码来四舍五入数据框中的浮动值a

a = pd.DataFrame([[1.2,3.4],[1.4,4.6]])
a = a.apply(round)
Run Code Online (Sandbox Code Playgroud)

但我得到的输出如下:

    0   1
0   1.0 3.0
1   1.0 5.0
Run Code Online (Sandbox Code Playgroud)

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

此外,按如下方式应用时,行为会有所不同:

round(0.5)
>>0
Run Code Online (Sandbox Code Playgroud)
x= [1.4,2.5,3.6]
list(map(round,x))

>>[1, 2, 4]
Run Code Online (Sandbox Code Playgroud)

为什么会出现这种异常现象?

cs9*_*s95 5

applyround连续调用每一列上的函数。DataFrame 列是Series对象,它们__round__定义了 dunder 方法,其行为略有不同。这实际上是round在 .NET 上调用时所调用的内容Series

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
Run Code Online (Sandbox Code Playgroud)

将此与 python 在标量上的典型行为进行对比round

round(1.5)
# 2

 # Same as,
(1.5).__round__()
# 2
Run Code Online (Sandbox Code Playgroud)

如果您想要相同的行为,请使用applymap.

a.applymap(round)

   0  1
0  1  3
1  1  5
Run Code Online (Sandbox Code Playgroud)

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

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

a.round().astype(int)

   0  1
0  1  3
1  1  5
Run Code Online (Sandbox Code Playgroud)

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