为了账号安全,请及时绑定邮箱和手机立即绑定

Python轮不返回整数

Python轮不返回整数

慕码人8056858 2021-11-02 20:24:49
我编写了以下代码来四舍五入数据帧中的浮动值 aa = pd.DataFrame([[1.2,3.4],[1.4,4.6]])a = a.apply(round)但我得到的输出如下:    0   10   1.0 3.01   1.0 5.0为什么函数返回四舍五入的浮点值而不是整数?此外,在应用如下时,行为是不同的:round(0.5)>>0x= [1.4,2.5,3.6]list(map(round,x))>>[1, 2, 4]为什么会出现这种异常?
查看完整描述

2 回答

?
萧十郎

TA贡献1815条经验 获得超13个赞

applyround连续调用每一列上的函数。DataFrame 列是Series对象,这些__round__列上定义了一个dunder 方法,其行为略有不同。这实际上是round调用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

将此与 Pythonround在标量上的典型行为进行对比:


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) 的列进行类型转换。


查看完整回答
反对 回复 2021-11-02
?
交互式爱情

TA贡献1712条经验 获得超3个赞

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

只需使用它astype即可将您floatinteger.


查看完整回答
反对 回复 2021-11-02
  • 2 回答
  • 0 关注
  • 176 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号