如何在Jupyter笔记本中为pandas.DataFrame.loc的输出设置精度?

时间:2018-10-30 10:15:39

标签: python pandas jupyter-notebook

在Jupyter笔记本中可以提高pandas.DataFrame.loc函数的表格输出的精度吗?

我希望在下表中看到$ f'_ {cds} $的输出以16位十进制数字精度表示:

Precision of the pandas.DataFrame.loc tabular output in a Jupyter notebookk

pd.set_option('precision', 16)

设置大熊猫的输出精度,但我希望能够仅针对$ f'_ {cds} $列设置精度。

这是我使用的示例数据集:

  

h,$ f' {ex} $,$ f' {fwd} $,$ E_ {fwd} $,$ E_ {fwdn} $,$ f' {cds } $,$ E {cds} $,$ E_ {cdsn} $   0.5,-0.2955202066613395,-0.5172595595568812,0.2217393528955416,0.750335672137813,-0.2833598684940762,0.01216033816726331,0.04114892279159381   0.25,-0.2955202066613395,-0.4112478682644012,0.1157276616030616,0.3916065940481806,-0.2924514766709212,0.003068729990418351,0.01038416298190755   0.125,-0.2955202066613395,-0.3543820493725782,0.05886184271123868,0.1991804329600149,-0.294751223803599,0.0007689828577405744,0.002602132918179141   0.0625,-0.2955202066613395,-0.325172396632464,0.02965218997112445,0.1003389592411367,-0.2953278482673038,0.0001923583940356965,0.0006509145219167214   0.03125,-0.2955202066613395,-0.3103980279268619,0.01487782126552234,0.05034451428416885,-0.2954721100178972,4.809664344235243e-05,0.0001627524695712948   0.015625,-0.2955202066613395,-0.3029715965360111,0.007451389874671588,0.02521448519156843,-0.2955081820601322,1.202460120736104e-05,4.068960746613514e-05   0.0078125,-0.2955202066613395,-0.2992489646633629,0.00372875800202338,0.01261760758815544,-0.2955172004835163,3.006177823283718e-06,1.017249499533797e-05   0.00390625,-0.2955202066613395,-0.297385344322862,0.001865137661522465,0.00631137099758419,-0.295519455115155,7.515461845630789e-07,2.543129598661713e-06   0.001953125,-0.2955202066613395,-0.2964529642682692,0.000932757606929624,0.003156324291551901,-0.2955200187747096,1.878866299764859e-07,6.357826833540365e-07   0.0009765625,-0.2955202066613395,-0.2959866325476241,0.0004664258862845938,0.001578321467604782,-0.2955201596896586,4.697168093370507e-08,1.589457501548573e-07

对于示例数据集,来自Mohit的答案如下:

sqrerr.loc[:, ("h","$E_{cds}$","$f'_{ex}$", "$f'_{cds}$")].style.format({"$f'_{cds}$" : '{:.16f}'})

3 个答案:

答案 0 :(得分:1)

使用df.style

df.style.format('{:.16f}')

让我知道它是否有效

对于列明智的操作:

df.style.format({'A': '{:.16f}', 'D': '{:.5f}'})

答案 1 :(得分:0)

在导入熊猫库后将这些行添加到您的代码中

pd.set_option('precision', 0) pd.set_option('display.float_format', lambda x: '%.0f' % x)

答案 2 :(得分:0)

df.style.format仅对当前输出设置精度。如果再次调用“ df”,则将与您导入的一样。

基于Malik Asad的回答,我在lambda函数中添加了if-else条件,以便您可以删除尾随零(.0)并为每个单元设置字面上的“个人”精度在数据框中具有数值:

        pd.set_option('display.float_format', lambda x: '%.0f' % x 
                      if (x == x and x*10 % 10 == 0) 
                      else ('%.1f' % x if (x == x and x*100 % 10 == 0)
                      else '%.2f' % x))

Example in Python

当然,您可以通过添加更多选项来改进它。