在Python pandas DataFram中,将浮点数四舍五入/近似为小数点后3位

2024-05-16 01:56:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一种情况,我将this csv file加载到pandas数据框中,并对某些列中的值求和。

除一列(名为:上升)外,大多数列的结果和四舍五入到小数点后3位。如何将总和(浮点数)四舍五入/近似为小数点后3位?

level-book

我在代码片段中尝试了下面列出的方法,最接近的方法是将总和舍入为:0.902000000000000002,而不是0.902

以下是我在《朱庇特笔记》中试过的内容:

import numpy as np
import pandas as pd

level_table = pd.read_csv("Level_Book.csv")
level_table.round(3)


BS = level_table["Back Sight"].sum()
FS = level_table["Fore Sight"].sum()
Rise = level_table["Rise"].sum()
Fall = level_table["Fall"].sum()

# I tried the below methods, the closest rounded the sum to: 0.90200000000000002 instead of 0.902
# Rise = np.around(Rise, decimals=3)
# Rise = np.ceil(Rise)
# Rise = np.round(Rise, decimals=3)
# Rise = Rise.apply(np.round())

BS, FS, Rise, Fall

输出=(4.127、4.127、0.902000000000000002、0.902)或(4.127、4.127、0.9019999999999、0.902)

预期产量=(4.127、4.127、0.902、0.902)

enter image description here


Tags: csvthe方法importpandasasnptable