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

当值为 3.0 时,使用以下构造删除小数精度 (. & 0),当值为 3.12345 时,四舍五入到小数点后 4 位


import pandas as pd

df1 = 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。


白板的微信
浏览 109回答 1
1回答

慕的地8271018

您需要将列转换为对象类型,使用dtype=object:df1["Price"] = np.array([int(x) if x%1==0 else round(x,4) for x in df1["Price"].values ], dtype=object)&nbsp; &nbsp; Price0&nbsp; &nbsp; &nbsp; &nbsp;11&nbsp; 2.12342&nbsp; &nbsp; &nbsp; &nbsp;33&nbsp; 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'>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python