Skip to main content
 首页 » 编程设计

python之是否可以根据它的值在 DataFrame 中设置 float 的精度

2024年10月17日8zlslch

假设我有以下 DataFrame 'df':

In [25]: df 
Out[25]:  
          0 
0  1000.000 
1     0.395 
2     1.530 
3     1.200 
4     0.550 

我希望大于一的数字显示两位小数,小于一的数字显示四位,如下所示:

         0 
0  1000.00 
1    0.395 
2     1.53 
3     1.20 
4    0.550 

最有效的方法是什么?

请您参考如下方法:

使用pd.set_option('display.float_format', your_format)
其中 your_format = lambda x: '{{:0.{}f}}'.format(2 if x > 1 else 4).format(x)

或者可以使用pd.option_context临时设置

your_format = lambda x: '{{:0.{}f}}'.format(2 if x > 1 else 4).format(x) 
with pd.option_context('display.float_format', your_format): 
    print(df) 
 
        0 
0 1000.00 
1  0.3950 
2    1.53 
3    1.20 
4  0.5500