pandas style options to latex
Asked Answered
B

3

19

Pandas has two nice functionalities I use a lot - that's the df.style... option and the df.to_latex() call. But I do not know how to combine both.

The .style option makes looking at tables much more pleasant. It lets you grasp information rapidly because of visual enhancements. This works perfectly in a jupyter notebook, for example. Here is an arbitrary example I copied from the documentation.

df.style.bar(subset=['A', 'B'], align='mid', color=['#d65f5f', '#5fba7d'])

This yields:

Dataframe with style columns

However, as nice as this looks in a jupyter notebook, I can not put this to latex code. I get the following error message instead, if chaining a 'to_latex()' call at the end of my visual enhancements: AttributeError: 'Styler' object has no attribute. Does that mean it's simply not possible, because the displayed colorful table is not a DataFrame object any more, but now a Styler object, now?

Is there any workaround? At least with easier tables, let's say where only cells have a single background color with respect to their value, instead of a 'complicated' bar graph.

Bedstraw answered 22/8, 2019 at 10:2 Comment(2)
Chaining to_latex() at the end of that call won't work because at that point it's a Styler object, not a dataframe. Have you tried using df.style.apply() then calling df.to_latex()? Or reassign the styled dataframe to an object then call to_latex()Fancywork
There's an open PR for this: github.com/pandas-dev/pandas/issues/21673Fala
K
2

As of pandas v1.3.0 these are now combined in pandas.io.formats.style.Styler.to_latex.

Kenley answered 15/10, 2021 at 14:50 Comment(0)
F
1

Instead of trying to export this formatting to bulky LaTeX markup, I would go the route explored already over in TeX.SE: add the functionality as LaTeX code that draws similar formatting based on the same data.

Fanchie answered 20/4, 2020 at 14:0 Comment(0)
R
1

I don't know how you can use latex directly but you can use df.to_html(). Once you get the html you can style it as you like and then use any of the following.

  1. Python's html2latex
  2. Website :HTML to TEX Converter
  3. Python's weasyprint
  4. Pandoc

Here is one latex package that I found on googling that talks about embedding html in latex. https://alvinalexander.com/blog/post/latex/use-html-package-in-latex-control-your-output/

I once only used latex and embedded images of tables when I used it.

Restraint answered 20/6, 2020 at 15:22 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.