panel icon indicating copy to clipboard operation
panel copied to clipboard

The `justify` parameter of `pn.pane.DataFrame` has no effect

Open ambrustorok opened this issue 1 year ago • 2 comments

When you create a DataFrame and want the texts to be aligned to the left, you can only do it by using custom CSS and not with the build-in arguments.

import pandas as pd
import numpy as np
import panel as pn

pn.extension()

header = pd.MultiIndex.from_product([['Semester1', 'Semester2'],
                                     ['Math', 'Science']])

df = pd.DataFrame(np.array([['Excellent', 85, 'Fair', 82],
                            ['Fair', 80, 'Excellent', 95],
                            ['Excellent', 92, 'Fair', 88],
                            ['Fair', 75, 'Excellent', 91]]),
                  index=['Student1', 'Student2', 'Student3', 'Student4'],
                  columns=header)

pn.pane.DataFrame(df, justify="left", align="start")

image

Expected output (made possible by using custom CSS)

pandas_left = """
* {
  text-align: left !important;
}

"""

pn.pane.DataFrame(df, stylesheets=[pandas_left])

image

ambrustorok avatar Apr 18 '24 09:04 ambrustorok

It appears there's two separate "issues" here:

  • align is a bokeh/panel property that is meant for aligning the component as a whole so this is not a real bug.
  • justify left is a pandas argument for the to_html method and is meant for left/right aligning the column headers. The problem is that it does not work via CSS but via a poorly supported and largely deprecated halign attribute on the <th> headers (see https://github.com/pandas-dev/pandas/issues/39951).

As far as I can tell the best guidance for left aligning the cells is currently to use Pandas Styler objects, i.e.:

df.style.set_properties(**{'text-align': 'right'})

I would however be happy to add a text_align parameter to the DataFrame component.

philippjfr avatar Apr 22 '24 07:04 philippjfr

Thanks @philippjfr!

My overall problem with left-aligning is that using

df.style.set_properties(**{'text-align': 'right'})

will change the type of the dataframe from pandas.core.frame.DataFrame to pandas.io.formats.style.Styler, which is incompatible with certain parameters of pn.pane.DataFrame (such as index or sparsify) which I need for certain display preferences.

These issues can be easily overcome using the CSS hacking I used in the exampe above.

ambrustorok avatar Apr 22 '24 07:04 ambrustorok