在 Python pandas DataFrame 中将浮点数舍入/近似到小数点后 3 位
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38812372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Round/Approximate a float number to 3 decimal place in Python pandas DataFrame
提问by Umar Yusuf
I have a situation where I loaded this csv fileinto pandas DataFrame and sum the values in some of the columns.
我有一种情况,我将此 csv 文件加载到 Pandas DataFrame 中,并对某些列中的值求和。
The resulting sum was rounded to 3 decimal place for most of the columns except one column (named: Rise). How do I round/approximate the sum (which is a float number) to 3 decimal places?
对于除一列(名为:Rise)之外的大多数列,所得总和四舍五入到小数点后 3 位。如何将总和(浮点数)四舍五入/近似为小数点后 3 位?
I tried the methods listed below in code snippet, the closest rounded the sum to: 0.90200000000000002instead of 0.902
我试着在代码片段下面列出的方法,最接近四舍五入总和:0.90200000000000002而不是0.902
Here is what I have tried in Jupyter note:-
这是我在 Jupyter 笔记中尝试过的:-
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
Output =(4.127, 4.127, 0.90200000000000002, 0.902) or (4.127, 4.127, 0.9019999999999999, 0.902)
输出 =(4.127, 4.127, 0.90200000000000002, 0.902) 或 (4.127, 4.127, 0.9019999999999999, 0.902)
Expected Output =(4.127, 4.127, 0.902, 0.902)
预期输出 =(4.127, 4.127, 0.902, 0.902)
回答by P.Sharma
You can do this simply by using apply function:
您只需使用 apply 函数即可完成此操作:
sleepstudy['Reaction'] =d['Column'].apply(lambda x: round(x, 3))
回答by Kshitij
This was solved by user2285236in a comment to the question.
这是由user2285236在对问题的评论中解决的。
Use the built-in round
function:
使用内置round
函数:
round(var_Name, value)
var_Name
is variable you want to round up andvalue
is an integer value of decimal places to which you want to round
var_Name
是你想要四舍五入的变量value
是您要舍入到的小数位数的整数值
Example:
例子:
>>> sum = 6.77765345098888
>>> round(sum, 3)
>>> sum
6.777