Python/Pandas 数据帧 - 当 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 无效。

您需要使用以下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

正如您在下面看到的,这些对象在必要时保持intfloat

[print (type(i)) for i in df1["Price"].values]
Out[1]
<class 'int'>
<class 'numpy.float64'>
<class 'int'>
<class 'numpy.float64'>

最新更新