Python回合不返回整数

时间:2019-02-08 22:33:33

标签: python python-3.x pandas

我编写了以下代码来舍入数据帧# move labels in opposite directions ggplot(data = dat, aes(x = x, y = value, color = var)) + geom_line() + geom_label(aes(label = value), nudge_y = ifelse(dat$var == "y2", 1, -1) * 1) 中的浮点值

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

为什么这个异常?

2 个答案:

答案 0 :(得分:3)

apply连续在每一列上调用round函数。 DataFrame列是Series对象,而these have a __round__ dunder method defined on them的行为则稍有不同。实际上,这是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)的列。

答案 1 :(得分:0)

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

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

相关问题