pythonpandasdataframe

Pandas precision not working for last dataframe column


I have a issue with pandas dataframe print not printing the last column with the requested precision. How to fix?

Here is the short code snippet of the printout:

print(dfy)
print(dfy.dtypes)
with pd.option_context('display.precision', 0):
    print(dfy)

The printout from the code snippet:

                    gas         prev      delta%
2023-10-01   818.851398          NaN         NaN
2023-11-01  2009.784005  1755.768035   14.467513
2023-12-01  2304.134123  2479.160200   -7.059894
2024-01-01  2647.367761  2524.686911    4.859250
2024-02-01  1685.694664  2070.363903  -18.579789
2024-03-01  1588.714377  1840.684792  -13.688950
2024-04-01  1376.973210  1385.102980   -0.586943
2024-05-01   605.798978   706.870375  -14.298434
2024-06-01   117.488287   155.409729  -24.400945
2024-07-01   163.644399   133.852727   22.257053
2024-08-01   129.027315   121.264696    6.401384
2024-09-01   625.730027   198.051683  215.942797
gas       float64
prev      float64
delta%    float64
dtype: object
             gas  prev  delta%
2023-10-01   819   NaN     NaN
2023-11-01  2010  1756   1e+01
2023-12-01  2304  2479  -7e+00
2024-01-01  2647  2525   5e+00
2024-02-01  1686  2070  -2e+01
2024-03-01  1589  1841  -1e+01
2024-04-01  1377  1385  -6e-01
2024-05-01   606   707  -1e+01
2024-06-01   117   155  -2e+01
2024-07-01   164   134   2e+01
2024-08-01   129   121   6e+00
2024-09-01   626   198   2e+02

Solution

  • This issue is due to -0.586943 which cannot be accurately represented with this precision.

    You should round:

    with pd.option_context('display.precision', 0):
        print(dfy.round())
    

    Output:

                 gas  prev  delta%
    2023-10-01   819   NaN     NaN
    2023-11-01  2010  1756      14
    2023-12-01  2304  2479      -7
    2024-01-01  2647  2525       5
    2024-02-01  1686  2070     -19
    2024-03-01  1589  1841     -14
    2024-04-01  1377  1385      -1
    2024-05-01   606   707     -14
    2024-06-01   117   155     -24
    2024-07-01   164   134      22
    2024-08-01   129   121       6
    2024-09-01   626   198     216
    

    For reference, without the offending row:

    with pd.option_context('display.precision', 0):
        print(dfy.drop('2024-04-01'))
    
                 gas  prev  delta%
    2023-10-01   819   NaN     NaN
    2023-11-01  2010  1756      14
    2023-12-01  2304  2479      -7
    2024-01-01  2647  2525       5
    2024-02-01  1686  2070     -19
    2024-03-01  1589  1841     -14
    2024-05-01   606   707     -14
    2024-06-01   117   155     -24
    2024-07-01   164   134      22
    2024-08-01   129   121       6
    2024-09-01   626   198     216