将Python pandas数据框中的每个数字舍入2位小数

Tri*_*ard 8 python rounding pandas

这可行,p_table.apply(pd.Series.round)但它没有小数位

文档说

import pandas as pd

Series.round(decimals=0, out=None)
Run Code Online (Sandbox Code Playgroud)

我试过这个,p_table.apply(pd.Series.round(2))但得到这个错误:

unbound method round() must be called with Series instance as first argument (got int instance instead)
Run Code Online (Sandbox Code Playgroud)

如何将数据框中的所有元素舍入到两位小数?

[编辑]想出来了.

import numpy as np
np.round(p_table, decimals=2)
Run Code Online (Sandbox Code Playgroud)

Tri*_*ard 13

import numpy as np
np.round(p_table, decimals=2)
Run Code Online (Sandbox Code Playgroud)


小智 12

从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
Run Code Online (Sandbox Code Playgroud)


ewa*_*lel 6

下面是使用Pandas 轮函数进行此操作的可重复示例示例。

# 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}) 
Run Code Online (Sandbox Code Playgroud)


小智 5

        A       B    C
0       t       8    10.958904
1       w       2    98.630137
Run Code Online (Sandbox Code Playgroud)

要舍入 C 列,您可以使用以下命令:

df['c']=df['c'].apply(lambda x:round(x,2))
Run Code Online (Sandbox Code Playgroud)

输出将是:

        A       B    C
0       t       8    10.96
1       w       2    98.63
Run Code Online (Sandbox Code Playgroud)


Muh*_*oni 5

对于那些不是因为想要对 DataFrame 进行四舍五入而只是想将显示值限制为n小数位而来到这里的人,pd.set_option请改为使用。此方法将使笔记本上所有打印的 DataFrame 遵循该选项。

import pandas as pd
pd.set_option('precision', 2)
Run Code Online (Sandbox Code Playgroud)

编辑:

要同时抑制科学记数法,请使用:

pd.set_option('float_format', '{:.2f}'.format)
Run Code Online (Sandbox Code Playgroud)

编辑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]}))
Run Code Online (Sandbox Code Playgroud)

编辑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]}))
Run Code Online (Sandbox Code Playgroud)

编辑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"))
Run Code Online (Sandbox Code Playgroud)

奖金:

用来numpy:

np.set_printoptions(precision=2,  # limit to two decimal places in printing numpy
                    suppress=True,  # suppress scientific notation in printing numpy
                   )
Run Code Online (Sandbox Code Playgroud)

了解更多信息:https ://numpy.org/doc/stable/reference/ generated/numpy.set_printoptions.html