[英]Python/Pandas Dataframe - Replace decimal precision with int value when 0 else round to n decimal places
当值为 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
正如您在下面看到的,对象在必要时保存int
和float
:
[print (type(i)) for i in df1["Price"].values]
Out[1]
<class 'int'>
<class 'numpy.float64'>
<class 'int'>
<class 'numpy.float64'>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.