将数字四舍五入到小数点后四位数

时间:2019-03-25 10:19:20

标签: python pandas

我正在规范化数据,并希望最终在小数点后存储四舍五入的四位数。

以下语句为我提供了归一化的结果,但是如何将每个数字四舍五入到小数点后的4位数字。

df_new = df.loc[:,"pos_score":"neg_sub_score"].div(100, axis=0)

原始内容:18.685714285714287

归一化之后:.1868(期望)

归一化后:.18685714285714287(当前)

1 个答案:

答案 0 :(得分:2)

如果需要下限值乘以100,请转换为整数并除以10000

df = pd.DataFrame({'pos_score':[18.68577,18.685714],
                   'neg_sub_score':[10.23, 12.536]})
print (df)
   pos_score  neg_sub_score
0  18.685770         10.230
1  18.685714         12.536

df_new1 = df.loc[:,"pos_score":"neg_sub_score"].mul(100).astype(int).div(10000)
print (df_new1)
   pos_score  neg_sub_score
0     0.1868         0.1023
1     0.1868         0.1253

但是如果需要取整值,请添加DataFrame.round,但输出不同:

df_new2 = df.loc[:,"pos_score":"neg_sub_score"].div(100).round(4)
print (df_new2)
   pos_score  neg_sub_score
0     0.1869         0.1023
1     0.1869         0.1254