-
-
Notifications
You must be signed in to change notification settings - Fork 18.1k
/
style.py
4169 lines (3555 loc) · 153 KB
/
style.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Module for applying conditional formatting to DataFrames and Series.
"""
from __future__ import annotations
from contextlib import contextmanager
import copy
from functools import partial
import operator
from typing import (
TYPE_CHECKING,
Callable,
overload,
)
import warnings
import numpy as np
from pandas._config import get_option
from pandas.compat._optional import import_optional_dependency
from pandas.util._decorators import (
Substitution,
doc,
)
from pandas.util._exceptions import find_stack_level
import pandas as pd
from pandas import (
IndexSlice,
RangeIndex,
)
import pandas.core.common as com
from pandas.core.frame import (
DataFrame,
Series,
)
from pandas.core.generic import NDFrame
from pandas.core.shared_docs import _shared_docs
from pandas.io.formats.format import save_to_buffer
jinja2 = import_optional_dependency("jinja2", extra="DataFrame.style requires jinja2.")
from pandas.io.formats.style_render import (
CSSProperties,
CSSStyles,
ExtFormatter,
StylerRenderer,
Subset,
Tooltips,
format_table_styles,
maybe_convert_css_to_tuples,
non_reducing_slice,
refactor_levels,
)
if TYPE_CHECKING:
from collections.abc import (
Generator,
Hashable,
Sequence,
)
from matplotlib.colors import Colormap
from pandas._typing import (
Any,
Axis,
AxisInt,
Concatenate,
FilePath,
IndexLabel,
IntervalClosedType,
Level,
P,
QuantileInterpolation,
Scalar,
Self,
StorageOptions,
T,
WriteBuffer,
WriteExcelBuffer,
)
from pandas import ExcelWriter
try:
import matplotlib as mpl
import matplotlib.pyplot as plt
has_mpl = True
except ImportError:
has_mpl = False
@contextmanager
def _mpl(func: Callable) -> Generator[tuple[Any, Any], None, None]:
if has_mpl:
yield plt, mpl
else:
raise ImportError(f"{func.__name__} requires matplotlib.")
####
# Shared Doc Strings
subset_args = """subset : label, array-like, IndexSlice, optional
A valid 2d input to `DataFrame.loc[<subset>]`, or, in the case of a 1d input
or single key, to `DataFrame.loc[:, <subset>]` where the columns are
prioritised, to limit ``data`` to *before* applying the function."""
properties_args = """props : str, default None
CSS properties to use for highlighting. If ``props`` is given, ``color``
is not used."""
coloring_args = """color : str, default '{default}'
Background color to use for highlighting."""
buffering_args = """buf : str, path object, file-like object, optional
String, path object (implementing ``os.PathLike[str]``), or file-like
object implementing a string ``write()`` function. If ``None``, the result is
returned as a string."""
encoding_args = """encoding : str, optional
Character encoding setting for file output (and meta tags if available).
Defaults to ``pandas.options.styler.render.encoding`` value of "utf-8"."""
#
###
class Styler(StylerRenderer):
r"""
Helps style a DataFrame or Series according to the data with HTML and CSS.
Parameters
----------
data : Series or DataFrame
Data to be styled - either a Series or DataFrame.
precision : int, optional
Precision to round floats to. If not given defaults to
``pandas.options.styler.format.precision``.
.. versionchanged:: 1.4.0
table_styles : list-like, default None
List of {selector: (attr, value)} dicts; see Notes.
uuid : str, default None
A unique identifier to avoid CSS collisions; generated automatically.
caption : str, tuple, default None
String caption to attach to the table. Tuple only used for LaTeX dual captions.
table_attributes : str, default None
Items that show up in the opening ``<table>`` tag
in addition to automatic (by default) id.
cell_ids : bool, default True
If True, each cell will have an ``id`` attribute in their HTML tag.
The ``id`` takes the form ``T_<uuid>_row<num_row>_col<num_col>``
where ``<uuid>`` is the unique identifier, ``<num_row>`` is the row
number and ``<num_col>`` is the column number.
na_rep : str, optional
Representation for missing values.
If ``na_rep`` is None, no special formatting is applied, and falls back to
``pandas.options.styler.format.na_rep``.
uuid_len : int, default 5
If ``uuid`` is not specified, the length of the ``uuid`` to randomly generate
expressed in hex characters, in range [0, 32].
decimal : str, optional
Character used as decimal separator for floats, complex and integers. If not
given uses ``pandas.options.styler.format.decimal``.
.. versionadded:: 1.3.0
thousands : str, optional, default None
Character used as thousands separator for floats, complex and integers. If not
given uses ``pandas.options.styler.format.thousands``.
.. versionadded:: 1.3.0
escape : str, optional
Use 'html' to replace the characters ``&``, ``<``, ``>``, ``'``, and ``"``
in cell display string with HTML-safe sequences.
Use 'latex' to replace the characters ``&``, ``%``, ``$``, ``#``, ``_``,
``{``, ``}``, ``~``, ``^``, and ``\`` in the cell display string with
LaTeX-safe sequences. Use 'latex-math' to replace the characters
the same way as in 'latex' mode, except for math substrings,
which either are surrounded by two characters ``$`` or start with
the character ``\(`` and end with ``\)``.
If not given uses ``pandas.options.styler.format.escape``.
.. versionadded:: 1.3.0
formatter : str, callable, dict, optional
Object to define how values are displayed. See ``Styler.format``. If not given
uses ``pandas.options.styler.format.formatter``.
.. versionadded:: 1.4.0
Attributes
----------
env : Jinja2 jinja2.Environment
template_html : Jinja2 Template
template_html_table : Jinja2 Template
template_html_style : Jinja2 Template
template_latex : Jinja2 Template
loader : Jinja2 Loader
See Also
--------
DataFrame.style : Return a Styler object containing methods for building
a styled HTML representation for the DataFrame.
Notes
-----
Most styling will be done by passing style functions into
``Styler.apply`` or ``Styler.map``. Style functions should
return values with strings containing CSS ``'attr: value'`` that will
be applied to the indicated cells.
If using in the Jupyter notebook, Styler has defined a ``_repr_html_``
to automatically render itself. Otherwise call Styler.to_html to get
the generated HTML.
CSS classes are attached to the generated HTML
* Index and Column names include ``index_name`` and ``level<k>``
where `k` is its level in a MultiIndex
* Index label cells include
* ``row_heading``
* ``row<n>`` where `n` is the numeric position of the row
* ``level<k>`` where `k` is the level in a MultiIndex
* Column label cells include
* ``col_heading``
* ``col<n>`` where `n` is the numeric position of the column
* ``level<k>`` where `k` is the level in a MultiIndex
* Blank cells include ``blank``
* Data cells include ``data``
* Trimmed cells include ``col_trim`` or ``row_trim``.
Any, or all, or these classes can be renamed by using the ``css_class_names``
argument in ``Styler.set_table_classes``, giving a value such as
*{"row": "MY_ROW_CLASS", "col_trim": "", "row_trim": ""}*.
Examples
--------
>>> df = pd.DataFrame([[1.0, 2.0, 3.0], [4, 5, 6]], index=['a', 'b'],
... columns=['A', 'B', 'C'])
>>> pd.io.formats.style.Styler(df, precision=2,
... caption="My table") # doctest: +SKIP
Please see:
`Table Visualization <../../user_guide/style.ipynb>`_ for more examples.
"""
def __init__(
self,
data: DataFrame | Series,
precision: int | None = None,
table_styles: CSSStyles | None = None,
uuid: str | None = None,
caption: str | tuple | list | None = None,
table_attributes: str | None = None,
cell_ids: bool = True,
na_rep: str | None = None,
uuid_len: int = 5,
decimal: str | None = None,
thousands: str | None = None,
escape: str | None = None,
formatter: ExtFormatter | None = None,
) -> None:
super().__init__(
data=data,
uuid=uuid,
uuid_len=uuid_len,
table_styles=table_styles,
table_attributes=table_attributes,
caption=caption,
cell_ids=cell_ids,
precision=precision,
)
# validate ordered args
thousands = thousands or get_option("styler.format.thousands")
decimal = decimal or get_option("styler.format.decimal")
na_rep = na_rep or get_option("styler.format.na_rep")
escape = escape or get_option("styler.format.escape")
formatter = formatter or get_option("styler.format.formatter")
# precision is handled by superclass as default for performance
self.format(
formatter=formatter,
precision=precision,
na_rep=na_rep,
escape=escape,
decimal=decimal,
thousands=thousands,
)
def concat(self, other: Styler) -> Styler:
"""
Append another Styler to combine the output into a single table.
.. versionadded:: 1.5.0
Parameters
----------
other : Styler
The other Styler object which has already been styled and formatted. The
data for this Styler must have the same columns as the original, and the
number of index levels must also be the same to render correctly.
Returns
-------
Styler
Notes
-----
The purpose of this method is to extend existing styled dataframes with other
metrics that may be useful but may not conform to the original's structure.
For example adding a sub total row, or displaying metrics such as means,
variance or counts.
Styles that are applied using the ``apply``, ``map``, ``apply_index``
and ``map_index``, and formatting applied with ``format`` and
``format_index`` will be preserved.
.. warning::
Only the output methods ``to_html``, ``to_string`` and ``to_latex``
currently work with concatenated Stylers.
Other output methods, including ``to_excel``, **do not** work with
concatenated Stylers.
The following should be noted:
- ``table_styles``, ``table_attributes``, ``caption`` and ``uuid`` are all
inherited from the original Styler and not ``other``.
- hidden columns and hidden index levels will be inherited from the
original Styler
- ``css`` will be inherited from the original Styler, and the value of
keys ``data``, ``row_heading`` and ``row`` will be prepended with
``foot0_``. If more concats are chained, their styles will be prepended
with ``foot1_``, ''foot_2'', etc., and if a concatenated style have
another concatanated style, the second style will be prepended with
``foot{parent}_foot{child}_``.
A common use case is to concatenate user defined functions with
``DataFrame.agg`` or with described statistics via ``DataFrame.describe``.
See examples.
Examples
--------
A common use case is adding totals rows, or otherwise, via methods calculated
in ``DataFrame.agg``.
>>> df = pd.DataFrame([[4, 6], [1, 9], [3, 4], [5, 5], [9, 6]],
... columns=["Mike", "Jim"],
... index=["Mon", "Tue", "Wed", "Thurs", "Fri"])
>>> styler = df.style.concat(df.agg(["sum"]).style) # doctest: +SKIP
.. figure:: ../../_static/style/footer_simple.png
Since the concatenated object is a Styler the existing functionality can be
used to conditionally format it as well as the original.
>>> descriptors = df.agg(["sum", "mean", lambda s: s.dtype])
>>> descriptors.index = ["Total", "Average", "dtype"]
>>> other = (descriptors.style
... .highlight_max(axis=1, subset=(["Total", "Average"], slice(None)))
... .format(subset=("Average", slice(None)), precision=2, decimal=",")
... .map(lambda v: "font-weight: bold;"))
>>> styler = (df.style
... .highlight_max(color="salmon")
... .set_table_styles([{"selector": ".foot_row0",
... "props": "border-top: 1px solid black;"}]))
>>> styler.concat(other) # doctest: +SKIP
.. figure:: ../../_static/style/footer_extended.png
When ``other`` has fewer index levels than the original Styler it is possible
to extend the index in ``other``, with placeholder levels.
>>> df = pd.DataFrame([[1], [2]],
... index=pd.MultiIndex.from_product([[0], [1, 2]]))
>>> descriptors = df.agg(["sum"])
>>> descriptors.index = pd.MultiIndex.from_product([[""], descriptors.index])
>>> df.style.concat(descriptors.style) # doctest: +SKIP
"""
if not isinstance(other, Styler):
raise TypeError("`other` must be of type `Styler`")
if not self.data.columns.equals(other.data.columns):
raise ValueError("`other.data` must have same columns as `Styler.data`")
if not self.data.index.nlevels == other.data.index.nlevels:
raise ValueError(
"number of index levels must be same in `other` "
"as in `Styler`. See documentation for suggestions."
)
self.concatenated.append(other)
return self
def _repr_html_(self) -> str | None:
"""
Hooks into Jupyter notebook rich display system, which calls _repr_html_ by
default if an object is returned at the end of a cell.
"""
if get_option("styler.render.repr") == "html":
return self.to_html()
return None
def _repr_latex_(self) -> str | None:
if get_option("styler.render.repr") == "latex":
return self.to_latex()
return None
def set_tooltips(
self,
ttips: DataFrame,
props: CSSProperties | None = None,
css_class: str | None = None,
) -> Styler:
"""
Set the DataFrame of strings on ``Styler`` generating ``:hover`` tooltips.
These string based tooltips are only applicable to ``<td>`` HTML elements,
and cannot be used for column or index headers.
.. versionadded:: 1.3.0
Parameters
----------
ttips : DataFrame
DataFrame containing strings that will be translated to tooltips, mapped
by identical column and index values that must exist on the underlying
Styler data. None, NaN values, and empty strings will be ignored and
not affect the rendered HTML.
props : list-like or str, optional
List of (attr, value) tuples or a valid CSS string. If ``None`` adopts
the internal default values described in notes.
css_class : str, optional
Name of the tooltip class used in CSS, should conform to HTML standards.
Only useful if integrating tooltips with external CSS. If ``None`` uses the
internal default value 'pd-t'.
Returns
-------
Styler
Notes
-----
Tooltips are created by adding `<span class="pd-t"></span>` to each data cell
and then manipulating the table level CSS to attach pseudo hover and pseudo
after selectors to produce the required the results.
The default properties for the tooltip CSS class are:
- visibility: hidden
- position: absolute
- z-index: 1
- background-color: black
- color: white
- transform: translate(-20px, -20px)
The property 'visibility: hidden;' is a key prerequisite to the hover
functionality, and should always be included in any manual properties
specification, using the ``props`` argument.
Tooltips are not designed to be efficient, and can add large amounts of
additional HTML for larger tables, since they also require that ``cell_ids``
is forced to `True`.
Examples
--------
Basic application
>>> df = pd.DataFrame(data=[[0, 1], [2, 3]])
>>> ttips = pd.DataFrame(
... data=[["Min", ""], [np.nan, "Max"]], columns=df.columns, index=df.index
... )
>>> s = df.style.set_tooltips(ttips).to_html()
Optionally controlling the tooltip visual display
>>> df.style.set_tooltips(ttips, css_class='tt-add', props=[
... ('visibility', 'hidden'),
... ('position', 'absolute'),
... ('z-index', 1)]) # doctest: +SKIP
>>> df.style.set_tooltips(
... ttips, css_class='tt-add',
... props='visibility:hidden; position:absolute; z-index:1;')
... # doctest: +SKIP
"""
if not self.cell_ids:
# tooltips not optimised for individual cell check. requires reasonable
# redesign and more extensive code for a feature that might be rarely used.
raise NotImplementedError(
"Tooltips can only render with 'cell_ids' is True."
)
if not ttips.index.is_unique or not ttips.columns.is_unique:
raise KeyError(
"Tooltips render only if `ttips` has unique index and columns."
)
if self.tooltips is None: # create a default instance if necessary
self.tooltips = Tooltips()
self.tooltips.tt_data = ttips
if props:
self.tooltips.class_properties = props
if css_class:
self.tooltips.class_name = css_class
return self
@doc(
NDFrame.to_excel,
klass="Styler",
storage_options=_shared_docs["storage_options"],
storage_options_versionadded="1.5.0",
)
def to_excel(
self,
excel_writer: FilePath | WriteExcelBuffer | ExcelWriter,
sheet_name: str = "Sheet1",
na_rep: str = "",
float_format: str | None = None,
columns: Sequence[Hashable] | None = None,
header: Sequence[Hashable] | bool = True,
index: bool = True,
index_label: IndexLabel | None = None,
startrow: int = 0,
startcol: int = 0,
engine: str | None = None,
merge_cells: bool = True,
encoding: str | None = None,
inf_rep: str = "inf",
verbose: bool = True,
freeze_panes: tuple[int, int] | None = None,
storage_options: StorageOptions | None = None,
) -> None:
from pandas.io.formats.excel import ExcelFormatter
formatter = ExcelFormatter(
self,
na_rep=na_rep,
cols=columns,
header=header,
float_format=float_format,
index=index,
index_label=index_label,
merge_cells=merge_cells,
inf_rep=inf_rep,
)
formatter.write(
excel_writer,
sheet_name=sheet_name,
startrow=startrow,
startcol=startcol,
freeze_panes=freeze_panes,
engine=engine,
storage_options=storage_options,
)
@overload
def to_latex(
self,
buf: FilePath | WriteBuffer[str],
*,
column_format: str | None = ...,
position: str | None = ...,
position_float: str | None = ...,
hrules: bool | None = ...,
clines: str | None = ...,
label: str | None = ...,
caption: str | tuple | None = ...,
sparse_index: bool | None = ...,
sparse_columns: bool | None = ...,
multirow_align: str | None = ...,
multicol_align: str | None = ...,
siunitx: bool = ...,
environment: str | None = ...,
encoding: str | None = ...,
convert_css: bool = ...,
) -> None:
...
@overload
def to_latex(
self,
buf: None = ...,
*,
column_format: str | None = ...,
position: str | None = ...,
position_float: str | None = ...,
hrules: bool | None = ...,
clines: str | None = ...,
label: str | None = ...,
caption: str | tuple | None = ...,
sparse_index: bool | None = ...,
sparse_columns: bool | None = ...,
multirow_align: str | None = ...,
multicol_align: str | None = ...,
siunitx: bool = ...,
environment: str | None = ...,
encoding: str | None = ...,
convert_css: bool = ...,
) -> str:
...
def to_latex(
self,
buf: FilePath | WriteBuffer[str] | None = None,
*,
column_format: str | None = None,
position: str | None = None,
position_float: str | None = None,
hrules: bool | None = None,
clines: str | None = None,
label: str | None = None,
caption: str | tuple | None = None,
sparse_index: bool | None = None,
sparse_columns: bool | None = None,
multirow_align: str | None = None,
multicol_align: str | None = None,
siunitx: bool = False,
environment: str | None = None,
encoding: str | None = None,
convert_css: bool = False,
) -> str | None:
r"""
Write Styler to a file, buffer or string in LaTeX format.
.. versionadded:: 1.3.0
Parameters
----------
buf : str, path object, file-like object, or None, default None
String, path object (implementing ``os.PathLike[str]``), or file-like
object implementing a string ``write()`` function. If None, the result is
returned as a string.
column_format : str, optional
The LaTeX column specification placed in location:
\\begin{tabular}{<column_format>}
Defaults to 'l' for index and
non-numeric data columns, and, for numeric data columns,
to 'r' by default, or 'S' if ``siunitx`` is ``True``.
position : str, optional
The LaTeX positional argument (e.g. 'h!') for tables, placed in location:
``\\begin{table}[<position>]``.
position_float : {"centering", "raggedleft", "raggedright"}, optional
The LaTeX float command placed in location:
\\begin{table}[<position>]
\\<position_float>
Cannot be used if ``environment`` is "longtable".
hrules : bool
Set to `True` to add \\toprule, \\midrule and \\bottomrule from the
{booktabs} LaTeX package.
Defaults to ``pandas.options.styler.latex.hrules``, which is `False`.
.. versionchanged:: 1.4.0
clines : str, optional
Use to control adding \\cline commands for the index labels separation.
Possible values are:
- `None`: no cline commands are added (default).
- `"all;data"`: a cline is added for every index value extending the
width of the table, including data entries.
- `"all;index"`: as above with lines extending only the width of the
index entries.
- `"skip-last;data"`: a cline is added for each index value except the
last level (which is never sparsified), extending the widtn of the
table.
- `"skip-last;index"`: as above with lines extending only the width of the
index entries.
.. versionadded:: 1.4.0
label : str, optional
The LaTeX label included as: \\label{<label>}.
This is used with \\ref{<label>} in the main .tex file.
caption : str, tuple, optional
If string, the LaTeX table caption included as: \\caption{<caption>}.
If tuple, i.e ("full caption", "short caption"), the caption included
as: \\caption[<caption[1]>]{<caption[0]>}.
sparse_index : bool, optional
Whether to sparsify the display of a hierarchical index. Setting to False
will display each explicit level element in a hierarchical key for each row.
Defaults to ``pandas.options.styler.sparse.index``, which is `True`.
sparse_columns : bool, optional
Whether to sparsify the display of a hierarchical index. Setting to False
will display each explicit level element in a hierarchical key for each
column. Defaults to ``pandas.options.styler.sparse.columns``, which
is `True`.
multirow_align : {"c", "t", "b", "naive"}, optional
If sparsifying hierarchical MultiIndexes whether to align text centrally,
at the top or bottom using the multirow package. If not given defaults to
``pandas.options.styler.latex.multirow_align``, which is `"c"`.
If "naive" is given renders without multirow.
.. versionchanged:: 1.4.0
multicol_align : {"r", "c", "l", "naive-l", "naive-r"}, optional
If sparsifying hierarchical MultiIndex columns whether to align text at
the left, centrally, or at the right. If not given defaults to
``pandas.options.styler.latex.multicol_align``, which is "r".
If a naive option is given renders without multicol.
Pipe decorators can also be added to non-naive values to draw vertical
rules, e.g. "\|r" will draw a rule on the left side of right aligned merged
cells.
.. versionchanged:: 1.4.0
siunitx : bool, default False
Set to ``True`` to structure LaTeX compatible with the {siunitx} package.
environment : str, optional
If given, the environment that will replace 'table' in ``\\begin{table}``.
If 'longtable' is specified then a more suitable template is
rendered. If not given defaults to
``pandas.options.styler.latex.environment``, which is `None`.
.. versionadded:: 1.4.0
encoding : str, optional
Character encoding setting. Defaults
to ``pandas.options.styler.render.encoding``, which is "utf-8".
convert_css : bool, default False
Convert simple cell-styles from CSS to LaTeX format. Any CSS not found in
conversion table is dropped. A style can be forced by adding option
`--latex`. See notes.
Returns
-------
str or None
If `buf` is None, returns the result as a string. Otherwise returns `None`.
See Also
--------
Styler.format: Format the text display value of cells.
Notes
-----
**Latex Packages**
For the following features we recommend the following LaTeX inclusions:
===================== ==========================================================
Feature Inclusion
===================== ==========================================================
sparse columns none: included within default {tabular} environment
sparse rows \\usepackage{multirow}
hrules \\usepackage{booktabs}
colors \\usepackage[table]{xcolor}
siunitx \\usepackage{siunitx}
bold (with siunitx) | \\usepackage{etoolbox}
| \\robustify\\bfseries
| \\sisetup{detect-all = true} *(within {document})*
italic (with siunitx) | \\usepackage{etoolbox}
| \\robustify\\itshape
| \\sisetup{detect-all = true} *(within {document})*
environment \\usepackage{longtable} if arg is "longtable"
| or any other relevant environment package
hyperlinks \\usepackage{hyperref}
===================== ==========================================================
**Cell Styles**
LaTeX styling can only be rendered if the accompanying styling functions have
been constructed with appropriate LaTeX commands. All styling
functionality is built around the concept of a CSS ``(<attribute>, <value>)``
pair (see `Table Visualization <../../user_guide/style.ipynb>`_), and this
should be replaced by a LaTeX
``(<command>, <options>)`` approach. Each cell will be styled individually
using nested LaTeX commands with their accompanied options.
For example the following code will highlight and bold a cell in HTML-CSS:
>>> df = pd.DataFrame([[1, 2], [3, 4]])
>>> s = df.style.highlight_max(axis=None,
... props='background-color:red; font-weight:bold;')
>>> s.to_html() # doctest: +SKIP
The equivalent using LaTeX only commands is the following:
>>> s = df.style.highlight_max(axis=None,
... props='cellcolor:{red}; bfseries: ;')
>>> s.to_latex() # doctest: +SKIP
Internally these structured LaTeX ``(<command>, <options>)`` pairs
are translated to the
``display_value`` with the default structure:
``\<command><options> <display_value>``.
Where there are multiple commands the latter is nested recursively, so that
the above example highlighted cell is rendered as
``\cellcolor{red} \bfseries 4``.
Occasionally this format does not suit the applied command, or
combination of LaTeX packages that is in use, so additional flags can be
added to the ``<options>``, within the tuple, to result in different
positions of required braces (the **default** being the same as ``--nowrap``):
=================================== ============================================
Tuple Format Output Structure
=================================== ============================================
(<command>,<options>) \\<command><options> <display_value>
(<command>,<options> ``--nowrap``) \\<command><options> <display_value>
(<command>,<options> ``--rwrap``) \\<command><options>{<display_value>}
(<command>,<options> ``--wrap``) {\\<command><options> <display_value>}
(<command>,<options> ``--lwrap``) {\\<command><options>} <display_value>
(<command>,<options> ``--dwrap``) {\\<command><options>}{<display_value>}
=================================== ============================================
For example the `textbf` command for font-weight
should always be used with `--rwrap` so ``('textbf', '--rwrap')`` will render a
working cell, wrapped with braces, as ``\textbf{<display_value>}``.
A more comprehensive example is as follows:
>>> df = pd.DataFrame([[1, 2.2, "dogs"], [3, 4.4, "cats"], [2, 6.6, "cows"]],
... index=["ix1", "ix2", "ix3"],
... columns=["Integers", "Floats", "Strings"])
>>> s = df.style.highlight_max(
... props='cellcolor:[HTML]{FFFF00}; color:{red};'
... 'textit:--rwrap; textbf:--rwrap;'
... )
>>> s.to_latex() # doctest: +SKIP
.. figure:: ../../_static/style/latex_1.png
**Table Styles**
Internally Styler uses its ``table_styles`` object to parse the
``column_format``, ``position``, ``position_float``, and ``label``
input arguments. These arguments are added to table styles in the format:
.. code-block:: python
set_table_styles([
{"selector": "column_format", "props": f":{column_format};"},
{"selector": "position", "props": f":{position};"},
{"selector": "position_float", "props": f":{position_float};"},
{"selector": "label", "props": f":{{{label.replace(':','§')}}};"}
], overwrite=False)
Exception is made for the ``hrules`` argument which, in fact, controls all three
commands: ``toprule``, ``bottomrule`` and ``midrule`` simultaneously. Instead of
setting ``hrules`` to ``True``, it is also possible to set each
individual rule definition, by manually setting the ``table_styles``,
for example below we set a regular ``toprule``, set an ``hline`` for
``bottomrule`` and exclude the ``midrule``:
.. code-block:: python
set_table_styles([
{'selector': 'toprule', 'props': ':toprule;'},
{'selector': 'bottomrule', 'props': ':hline;'},
], overwrite=False)
If other ``commands`` are added to table styles they will be detected, and
positioned immediately above the '\\begin{tabular}' command. For example to
add odd and even row coloring, from the {colortbl} package, in format
``\rowcolors{1}{pink}{red}``, use:
.. code-block:: python
set_table_styles([
{'selector': 'rowcolors', 'props': ':{1}{pink}{red};'}
], overwrite=False)
A more comprehensive example using these arguments is as follows:
>>> df.columns = pd.MultiIndex.from_tuples([
... ("Numeric", "Integers"),
... ("Numeric", "Floats"),
... ("Non-Numeric", "Strings")
... ])
>>> df.index = pd.MultiIndex.from_tuples([
... ("L0", "ix1"), ("L0", "ix2"), ("L1", "ix3")
... ])
>>> s = df.style.highlight_max(
... props='cellcolor:[HTML]{FFFF00}; color:{red}; itshape:; bfseries:;'
... )
>>> s.to_latex(
... column_format="rrrrr", position="h", position_float="centering",
... hrules=True, label="table:5", caption="Styled LaTeX Table",
... multirow_align="t", multicol_align="r"
... ) # doctest: +SKIP
.. figure:: ../../_static/style/latex_2.png
**Formatting**
To format values :meth:`Styler.format` should be used prior to calling
`Styler.to_latex`, as well as other methods such as :meth:`Styler.hide`
for example:
>>> s.clear()
>>> s.table_styles = []
>>> s.caption = None
>>> s.format({
... ("Numeric", "Integers"): '\\${}',
... ("Numeric", "Floats"): '{:.3f}',
... ("Non-Numeric", "Strings"): str.upper
... }) # doctest: +SKIP
Numeric Non-Numeric
Integers Floats Strings
L0 ix1 $1 2.200 DOGS
ix2 $3 4.400 CATS
L1 ix3 $2 6.600 COWS
>>> s.to_latex() # doctest: +SKIP
\begin{tabular}{llrrl}
{} & {} & \multicolumn{2}{r}{Numeric} & {Non-Numeric} \\
{} & {} & {Integers} & {Floats} & {Strings} \\
\multirow[c]{2}{*}{L0} & ix1 & \\$1 & 2.200 & DOGS \\
& ix2 & \$3 & 4.400 & CATS \\
L1 & ix3 & \$2 & 6.600 & COWS \\
\end{tabular}
**CSS Conversion**
This method can convert a Styler constructured with HTML-CSS to LaTeX using
the following limited conversions.
================== ==================== ============= ==========================
CSS Attribute CSS value LaTeX Command LaTeX Options
================== ==================== ============= ==========================
font-weight | bold | bfseries
| bolder | bfseries
font-style | italic | itshape
| oblique | slshape
background-color | red cellcolor | {red}--lwrap
| #fe01ea | [HTML]{FE01EA}--lwrap
| #f0e | [HTML]{FF00EE}--lwrap
| rgb(128,255,0) | [rgb]{0.5,1,0}--lwrap
| rgba(128,0,0,0.5) | [rgb]{0.5,0,0}--lwrap
| rgb(25%,255,50%) | [rgb]{0.25,1,0.5}--lwrap
color | red color | {red}
| #fe01ea | [HTML]{FE01EA}
| #f0e | [HTML]{FF00EE}
| rgb(128,255,0) | [rgb]{0.5,1,0}
| rgba(128,0,0,0.5) | [rgb]{0.5,0,0}
| rgb(25%,255,50%) | [rgb]{0.25,1,0.5}
================== ==================== ============= ==========================
It is also possible to add user-defined LaTeX only styles to a HTML-CSS Styler
using the ``--latex`` flag, and to add LaTeX parsing options that the
converter will detect within a CSS-comment.
>>> df = pd.DataFrame([[1]])
>>> df.style.set_properties(
... **{"font-weight": "bold /* --dwrap */", "Huge": "--latex--rwrap"}
... ).to_latex(convert_css=True) # doctest: +SKIP
\begin{tabular}{lr}
{} & {0} \\
0 & {\bfseries}{\Huge{1}} \\
\end{tabular}
Examples
--------
Below we give a complete step by step example adding some advanced features
and noting some common gotchas.
First we create the DataFrame and Styler as usual, including MultiIndex rows
and columns, which allow for more advanced formatting options:
>>> cidx = pd.MultiIndex.from_arrays([
... ["Equity", "Equity", "Equity", "Equity",
... "Stats", "Stats", "Stats", "Stats", "Rating"],
... ["Energy", "Energy", "Consumer", "Consumer", "", "", "", "", ""],
... ["BP", "Shell", "H&M", "Unilever",
... "Std Dev", "Variance", "52w High", "52w Low", ""]
... ])
>>> iidx = pd.MultiIndex.from_arrays([
... ["Equity", "Equity", "Equity", "Equity"],
... ["Energy", "Energy", "Consumer", "Consumer"],
... ["BP", "Shell", "H&M", "Unilever"]
... ])
>>> styler = pd.DataFrame([
... [1, 0.8, 0.66, 0.72, 32.1678, 32.1678**2, 335.12, 240.89, "Buy"],
... [0.8, 1.0, 0.69, 0.79, 1.876, 1.876**2, 14.12, 19.78, "Hold"],
... [0.66, 0.69, 1.0, 0.86, 7, 7**2, 210.9, 140.6, "Buy"],
... [0.72, 0.79, 0.86, 1.0, 213.76, 213.76**2, 2807, 3678, "Sell"],
... ], columns=cidx, index=iidx).style
Second we will format the display and, since our table is quite wide, will
hide the repeated level-0 of the index:
>>> (styler.format(subset="Equity", precision=2)
... .format(subset="Stats", precision=1, thousands=",")
... .format(subset="Rating", formatter=str.upper)
... .format_index(escape="latex", axis=1)
... .format_index(escape="latex", axis=0)
... .hide(level=0, axis=0)) # doctest: +SKIP
Note that one of the string entries of the index and column headers is "H&M".
Without applying the `escape="latex"` option to the `format_index` method the
resultant LaTeX will fail to render, and the error returned is quite
difficult to debug. Using the appropriate escape the "&" is converted to "\\&".