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

当 0 舍入到 n 位小数时,用 int 值替换小数精度

当 0 舍入到 n 位小数时,用 int 值替换小数精度

白板的微信 2022-07-12 15:42:28
当值为 3.0 时,使用以下构造删除小数精度 (. & 0),当值为 3.12345 时,四舍五入到小数点后 4 位import pandas as pddf1 = pd.DataFrame({'Price':[1.0,2.12345,3.0,4.67892]})df1["Price"] = df1["Price"].apply(lambda x: round(x,4) if x%1 else int(x))print(df1)舍入有效,但不能转换为 int。
查看完整描述

1 回答

?
慕的地8271018

TA贡献1796条经验 获得超4个赞

您需要将列转换为对象类型,使用dtype=object:


df1["Price"] = np.array([int(x) if x%1==0 else round(x,4) for x in df1["Price"].values ], dtype=object)


    Price

0       1

1  2.1234

2       3

3  4.6789

正如您在下面看到的,对象int在float必要时保持:


[print (type(i)) for i in df1["Price"].values]


Out[1]

<class 'int'>

<class 'numpy.float64'>

<class 'int'>

<class 'numpy.float64'>


查看完整回答
反对 回复 2022-07-12
  • 1 回答
  • 0 关注
  • 108 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

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

帮助反馈 APP下载

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

公众号

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