在Python pandas数据框中将每个数字四舍五入到小数点后两位
这个方法 p_table.apply(pd.Series.round)
可以用,但它没有小数位。
import pandas as pd
Series.round(decimals=0, out=None)
我试过这个 p_table.apply(pd.Series.round(2))
,但是出现了这个错误:
unbound method round() must be called with Series instance as first argument (got int instance instead)
我该如何把数据表中的所有元素都四舍五入到小数点后两位呢?
6 个回答
5
如果你来到这里不是因为想要对数据框进行四舍五入,而只是想限制显示的小数位数到n
位,可以使用pd.set_option
。这个方法会让你在笔记本上打印的所有数据框都遵循这个设置。
import pandas as pd
pd.set_option('precision', 2)
编辑:
如果你还想去掉科学计数法,可以使用:
pd.set_option('float_format', '{:.2f}'.format)
编辑 2:
结合使用IPython和pandas的选项上下文管理器,你可以这样做:
from IPython.display import display
with pd.option_context('precision', 3,
'float_format', '{:.2f}'.format):
display(pd.DataFrame(data={'x':[1,2,3],
'y':[4,5,6]}))
编辑 3:
最新版本的pandas对set_option
进行了更改。我不太确定具体是什么时候改的,但在1.5.1版本及之后的版本中,使用'display.precision'
来代替'precision'
:
from IPython.display import display
with pd.option_context('display.precision', 3,
'display.float_format', '{:.2f}'.format):
display(pd.DataFrame(data={'x':[1,2,3],
'y':[4,5,6]}))
编辑 4:
如果你的数据框是Styler对象,可以使用pd.set_option('styler.format.precision', 2)
。你可以在我之前的回答中找到更多信息,链接在这里 这里
import numpy as np
import pandas as pd
from IPython.display import display
pd.set_option('styler.format.precision', 2)
df = pd.DataFrame(
np.random.random(size=(2, 3))
)
display(df.style.set_caption("Styler precision"))
额外提示:
对于numpy
,可以使用:
np.set_printoptions(precision=2, # limit to two decimal places in printing numpy
suppress=True, # suppress scientific notation in printing numpy
)
想了解更多,请访问: https://numpy.org/doc/stable/reference/generated/numpy.set_printoptions.html
8
A B C
0 t 8 10.958904
1 w 2 98.630137
要对C列进行四舍五入,你可以使用这个:
df['c']=df['c'].apply(lambda x:round(x,2))
输出结果将会是:
A B C
0 t 8 10.96
1 w 2 98.63
16
下面是一个使用 pandas 的 round 函数来实现的示例,方法简单易复现。
# importing pandas as pd
import pandas as pd
# generate sample dataframe
df = pd.DataFrame(np.random.random([5, 4]), columns =["A", "B", "C"])
# use pandas dataframe.round()function to round off all the decimal values to 2 decimal
df.round(2)
# If you want to customize the round off by individual columns
df.round({"A":1, "B":2, "C":3})
48
从 0.17.0
版本开始,你可以使用 .round(n)
这个功能。
df.round(2)
0 1 2 3
0 0.06 0.67 0.77 0.71
1 0.80 0.56 0.97 0.15
2 0.03 0.59 0.11 0.95
3 0.33 0.19 0.46 0.92
df
0 1 2 3
0 0.057116 0.669422 0.767117 0.708115
1 0.796867 0.557761 0.965837 0.147157
2 0.029647 0.593893 0.114066 0.950810
3 0.325707 0.193619 0.457812 0.920403
25
import numpy as np
np.round(p_table, decimals=2)
当然可以!请把你想要翻译的内容发给我,我会帮你把它变得简单易懂。