Search code examples
pythonpandaslatexprecision

Pandas Dataframe Display Precision by row


I am using pandas to output my results to LaTeX. I currently set my precision (number of decimals to print out) as follows:

import pandas as pd
df = pd.DataFrame({'a':[1234.56, 0.01, 1234.56],'b':[1234.56, 0.01, 1234.56]})

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

df.to_latex('filename.tex')

This works really well. But I would like the precision to be different for specific rows of my dataframe (and resulting TeX table). Is it possible to do this with pandas?

For this example, I want rows 0 and 2 to print with no decimal places and row 1 to print with 2 decimal places, as follows:

 df
      a     b
 0    1234  1234
 1    0.01  0.01
 2    1234  1234

Solution

  • This is a crappy answer and I'm too tired to think of a better one. But I didn't want to leave you hanging after I half lectured you on question quality.

    p = pd.Series([1, 2, 0], df.index)
    
    df.apply(lambda x: x.map(p.map(lambda x: '{{:0.{}f}}'.format(x).format).loc[x.name]), 1)
    
            a       b
    0  1234.6  1234.6
    1    0.01    0.01
    2    1235    1235