forked from pandas-dev/pandas
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstyle_render.py
1524 lines (1307 loc) · 54 KB
/
style_render.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
from __future__ import annotations
from collections import defaultdict
from functools import partial
import re
from typing import (
Any,
Callable,
DefaultDict,
Dict,
List,
Optional,
Sequence,
Tuple,
TypedDict,
Union,
)
from uuid import uuid4
import numpy as np
from pandas._config import get_option
from pandas._libs import lib
from pandas.compat._optional import import_optional_dependency
from pandas.core.dtypes.generic import ABCSeries
from pandas import (
DataFrame,
Index,
IndexSlice,
MultiIndex,
Series,
isna,
)
from pandas.api.types import is_list_like
import pandas.core.common as com
jinja2 = import_optional_dependency("jinja2", extra="DataFrame.style requires jinja2.")
from markupsafe import escape as escape_html # markupsafe is jinja2 dependency
BaseFormatter = Union[str, Callable]
ExtFormatter = Union[BaseFormatter, Dict[Any, Optional[BaseFormatter]]]
CSSPair = Tuple[str, Union[str, int, float]]
CSSList = List[CSSPair]
CSSProperties = Union[str, CSSList]
class CSSDict(TypedDict):
selector: str
props: CSSProperties
CSSStyles = List[CSSDict]
Subset = Union[slice, Sequence, Index]
class StylerRenderer:
"""
Base class to process rendering a Styler with a specified jinja2 template.
"""
loader = jinja2.PackageLoader("pandas", "io/formats/templates")
env = jinja2.Environment(loader=loader, trim_blocks=True)
template_html = env.get_template("html.tpl")
template_html_table = env.get_template("html_table.tpl")
template_html_style = env.get_template("html_style.tpl")
template_latex = env.get_template("latex.tpl")
def __init__(
self,
data: DataFrame | Series,
uuid: str | None = None,
uuid_len: int = 5,
table_styles: CSSStyles | None = None,
table_attributes: str | None = None,
caption: str | tuple | None = None,
cell_ids: bool = True,
):
# validate ordered args
if isinstance(data, Series):
data = data.to_frame()
if not isinstance(data, DataFrame):
raise TypeError("``data`` must be a Series or DataFrame")
self.data: DataFrame = data
self.index: Index = data.index
self.columns: Index = data.columns
if not isinstance(uuid_len, int) or not uuid_len >= 0:
raise TypeError("``uuid_len`` must be an integer in range [0, 32].")
self.uuid_len = min(32, uuid_len)
self.uuid = uuid or uuid4().hex[: self.uuid_len]
self.table_styles = table_styles
self.table_attributes = table_attributes
self.caption = caption
self.cell_ids = cell_ids
# add rendering variables
self.hide_index_: list = [False] * self.index.nlevels
self.hide_columns_: list = [False] * self.columns.nlevels
self.hidden_rows: Sequence[int] = [] # sequence for specific hidden rows/cols
self.hidden_columns: Sequence[int] = []
self.ctx: DefaultDict[tuple[int, int], CSSList] = defaultdict(list)
self.ctx_index: DefaultDict[tuple[int, int], CSSList] = defaultdict(list)
self.ctx_columns: DefaultDict[tuple[int, int], CSSList] = defaultdict(list)
self.cell_context: DefaultDict[tuple[int, int], str] = defaultdict(str)
self._todo: list[tuple[Callable, tuple, dict]] = []
self.tooltips: Tooltips | None = None
def_precision = get_option("display.precision")
self._display_funcs: DefaultDict[ # maps (row, col) -> formatting function
tuple[int, int], Callable[[Any], str]
] = defaultdict(lambda: partial(_default_formatter, precision=def_precision))
def _render_html(self, sparse_index: bool, sparse_columns: bool, **kwargs) -> str:
"""
Renders the ``Styler`` including all applied styles to HTML.
Generates a dict with necessary kwargs passed to jinja2 template.
"""
self._compute()
# TODO: namespace all the pandas keys
d = self._translate(sparse_index, sparse_columns)
d.update(kwargs)
return self.template_html.render(
**d,
html_table_tpl=self.template_html_table,
html_style_tpl=self.template_html_style,
)
def _render_latex(self, sparse_index: bool, sparse_columns: bool, **kwargs) -> str:
"""
Render a Styler in latex format
"""
self._compute()
d = self._translate(sparse_index, sparse_columns, blank="")
self._translate_latex(d)
self.template_latex.globals["parse_wrap"] = _parse_latex_table_wrapping
self.template_latex.globals["parse_table"] = _parse_latex_table_styles
self.template_latex.globals["parse_cell"] = _parse_latex_cell_styles
self.template_latex.globals["parse_header"] = _parse_latex_header_span
d.update(kwargs)
return self.template_latex.render(**d)
def _compute(self):
"""
Execute the style functions built up in `self._todo`.
Relies on the conventions that all style functions go through
.apply or .applymap. The append styles to apply as tuples of
(application method, *args, **kwargs)
"""
self.ctx.clear()
self.ctx_index.clear()
self.ctx_columns.clear()
r = self
for func, args, kwargs in self._todo:
r = func(self)(*args, **kwargs)
return r
def _translate(self, sparse_index: bool, sparse_cols: bool, blank: str = " "):
"""
Process Styler data and settings into a dict for template rendering.
Convert data and settings from ``Styler`` attributes such as ``self.data``,
``self.tooltips`` including applying any methods in ``self._todo``.
Parameters
----------
sparse_index : bool
Whether to sparsify the index or print all hierarchical index elements.
Upstream defaults are typically to `pandas.options.styler.sparse.index`.
sparse_cols : bool
Whether to sparsify the columns or print all hierarchical column elements.
Upstream defaults are typically to `pandas.options.styler.sparse.columns`.
Returns
-------
d : dict
The following structure: {uuid, table_styles, caption, head, body,
cellstyle, table_attributes}
"""
ROW_HEADING_CLASS = "row_heading"
COL_HEADING_CLASS = "col_heading"
INDEX_NAME_CLASS = "index_name"
TRIMMED_COL_CLASS = "col_trim"
TRIMMED_ROW_CLASS = "row_trim"
DATA_CLASS = "data"
BLANK_CLASS = "blank"
BLANK_VALUE = blank
# construct render dict
d = {
"uuid": self.uuid,
"table_styles": _format_table_styles(self.table_styles or []),
"caption": self.caption,
}
max_elements = get_option("styler.render.max_elements")
max_rows, max_cols = _get_trimming_maximums(
len(self.data.index), len(self.data.columns), max_elements
)
self.cellstyle_map_columns: DefaultDict[
tuple[CSSPair, ...], list[str]
] = defaultdict(list)
head = self._translate_header(
BLANK_CLASS,
BLANK_VALUE,
INDEX_NAME_CLASS,
COL_HEADING_CLASS,
sparse_cols,
max_cols,
TRIMMED_COL_CLASS,
)
d.update({"head": head})
self.cellstyle_map: DefaultDict[tuple[CSSPair, ...], list[str]] = defaultdict(
list
)
self.cellstyle_map_index: DefaultDict[
tuple[CSSPair, ...], list[str]
] = defaultdict(list)
body = self._translate_body(
DATA_CLASS,
ROW_HEADING_CLASS,
sparse_index,
max_rows,
max_cols,
TRIMMED_ROW_CLASS,
TRIMMED_COL_CLASS,
)
d.update({"body": body})
ctx_maps = {
"cellstyle": "cellstyle_map",
"cellstyle_index": "cellstyle_map_index",
"cellstyle_columns": "cellstyle_map_columns",
} # add the cell_ids styles map to the render dictionary in right format
for k, attr in ctx_maps.items():
map = [
{"props": list(props), "selectors": selectors}
for props, selectors in getattr(self, attr).items()
]
d.update({k: map})
table_attr = self.table_attributes
use_mathjax = get_option("display.html.use_mathjax")
if not use_mathjax:
table_attr = table_attr or ""
if 'class="' in table_attr:
table_attr = table_attr.replace('class="', 'class="tex2jax_ignore ')
else:
table_attr += ' class="tex2jax_ignore"'
d.update({"table_attributes": table_attr})
if self.tooltips:
d = self.tooltips._translate(self.data, self.uuid, d)
return d
def _translate_header(
self,
blank_class: str,
blank_value: str,
index_name_class: str,
col_heading_class: str,
sparsify_cols: bool,
max_cols: int,
trimmed_col_class: str,
):
"""
Build each <tr> within table <head> as a list
Using the structure:
+----------------------------+---------------+---------------------------+
| index_blanks ... | column_name_0 | column_headers (level_0) |
1) | .. | .. | .. |
| index_blanks ... | column_name_n | column_headers (level_n) |
+----------------------------+---------------+---------------------------+
2) | index_names (level_0 to level_n) ... | column_blanks ... |
+----------------------------+---------------+---------------------------+
Parameters
----------
blank_class : str
CSS class added to elements within blank sections of the structure.
blank_value : str
HTML display value given to elements within blank sections of the structure.
index_name_class : str
CSS class added to elements within the index_names section of the structure.
col_heading_class : str
CSS class added to elements within the column_names section of structure.
sparsify_cols : bool
Whether column_headers section will add colspan attributes (>1) to elements.
max_cols : int
Maximum number of columns to render. If exceeded will contain `...` filler.
trimmed_col_class : str
CSS class added to elements within a column including `...` trimmed vals.
Returns
-------
head : list
The associated HTML elements needed for template rendering.
"""
# for sparsifying a MultiIndex
col_lengths = _get_level_lengths(
self.columns, sparsify_cols, max_cols, self.hidden_columns
)
clabels = self.data.columns.tolist()[:max_cols] # slice to allow trimming
if self.data.columns.nlevels == 1:
clabels = [[x] for x in clabels]
clabels = list(zip(*clabels))
head = []
# 1) column headers
for r, hide in enumerate(self.hide_columns_):
if hide:
continue
else:
# number of index blanks is governed by number of hidden index levels
index_blanks = [_element("th", blank_class, blank_value, True)] * (
self.index.nlevels - sum(self.hide_index_) - 1
)
name = self.data.columns.names[r]
column_name = [
_element(
"th",
f"{blank_class if name is None else index_name_class} level{r}",
name if name is not None else blank_value,
not all(self.hide_index_),
)
]
if clabels:
column_headers = []
for c, value in enumerate(clabels[r]):
header_element = _element(
"th",
f"{col_heading_class} level{r} col{c}",
value,
_is_visible(c, r, col_lengths),
attributes=(
f'colspan="{col_lengths.get((r, c), 0)}"'
if col_lengths.get((r, c), 0) > 1
else ""
),
)
if self.cell_ids:
header_element["id"] = f"level{r}_col{c}"
if (r, c) in self.ctx_columns and self.ctx_columns[r, c]:
header_element["id"] = f"level{r}_col{c}"
self.cellstyle_map_columns[
tuple(self.ctx_columns[r, c])
].append(f"level{r}_col{c}")
column_headers.append(header_element)
if len(self.data.columns) > max_cols:
# add an extra column with `...` value to indicate trimming
column_headers.append(
_element(
"th",
f"{col_heading_class} level{r} {trimmed_col_class}",
"...",
True,
attributes="",
)
)
head.append(index_blanks + column_name + column_headers)
# 2) index names
if (
self.data.index.names
and com.any_not_none(*self.data.index.names)
and not all(self.hide_index_)
and not all(self.hide_columns_)
):
index_names = [
_element(
"th",
f"{index_name_class} level{c}",
blank_value if name is None else name,
not self.hide_index_[c],
)
for c, name in enumerate(self.data.index.names)
]
if len(self.data.columns) <= max_cols:
blank_len = len(clabels[0])
else:
blank_len = len(clabels[0]) + 1 # to allow room for `...` trim col
column_blanks = [
_element(
"th",
f"{blank_class} col{c}",
blank_value,
c not in self.hidden_columns,
)
for c in range(blank_len)
]
head.append(index_names + column_blanks)
return head
def _translate_body(
self,
data_class: str,
row_heading_class: str,
sparsify_index: bool,
max_rows: int,
max_cols: int,
trimmed_row_class: str,
trimmed_col_class: str,
):
"""
Build each <tr> within table <body> as a list
Use the following structure:
+--------------------------------------------+---------------------------+
| index_header_0 ... index_header_n | data_by_column |
+--------------------------------------------+---------------------------+
Also add elements to the cellstyle_map for more efficient grouped elements in
<style></style> block
Parameters
----------
data_class : str
CSS class added to elements within data_by_column sections of the structure.
row_heading_class : str
CSS class added to elements within the index_header section of structure.
sparsify_index : bool
Whether index_headers section will add rowspan attributes (>1) to elements.
Returns
-------
body : list
The associated HTML elements needed for template rendering.
"""
# for sparsifying a MultiIndex
idx_lengths = _get_level_lengths(
self.index, sparsify_index, max_rows, self.hidden_rows
)
rlabels = self.data.index.tolist()[:max_rows] # slice to allow trimming
if self.data.index.nlevels == 1:
rlabels = [[x] for x in rlabels]
body = []
for r, row_tup in enumerate(self.data.itertuples()):
if r >= max_rows: # used only to add a '...' trimmed row:
index_headers = [
_element(
"th",
f"{row_heading_class} level{c} {trimmed_row_class}",
"...",
not self.hide_index_[c],
attributes="",
)
for c in range(self.data.index.nlevels)
]
data = [
_element(
"td",
f"{data_class} col{c} {trimmed_row_class}",
"...",
(c not in self.hidden_columns),
attributes="",
)
for c in range(max_cols)
]
if len(self.data.columns) > max_cols:
# columns are also trimmed so we add the final element
data.append(
_element(
"td",
f"{data_class} {trimmed_row_class} {trimmed_col_class}",
"...",
True,
attributes="",
)
)
body.append(index_headers + data)
break
index_headers = []
for c, value in enumerate(rlabels[r]):
header_element = _element(
"th",
f"{row_heading_class} level{c} row{r}",
value,
(_is_visible(r, c, idx_lengths) and not self.hide_index_[c]),
attributes=(
f'rowspan="{idx_lengths.get((c, r), 0)}"'
if idx_lengths.get((c, r), 0) > 1
else ""
),
)
if self.cell_ids:
header_element["id"] = f"level{c}_row{r}" # id is specified
if (r, c) in self.ctx_index and self.ctx_index[r, c]:
# always add id if a style is specified
header_element["id"] = f"level{c}_row{r}"
self.cellstyle_map_index[tuple(self.ctx_index[r, c])].append(
f"level{c}_row{r}"
)
index_headers.append(header_element)
data = []
for c, value in enumerate(row_tup[1:]):
if c >= max_cols:
data.append(
_element(
"td",
f"{data_class} row{r} {trimmed_col_class}",
"...",
True,
attributes="",
)
)
break
# add custom classes from cell context
cls = ""
if (r, c) in self.cell_context:
cls = " " + self.cell_context[r, c]
data_element = _element(
"td",
f"{data_class} row{r} col{c}{cls}",
value,
(c not in self.hidden_columns and r not in self.hidden_rows),
attributes="",
display_value=self._display_funcs[(r, c)](value),
)
if self.cell_ids:
data_element["id"] = f"row{r}_col{c}"
if (r, c) in self.ctx and self.ctx[r, c]:
# always add id if needed due to specified style
data_element["id"] = f"row{r}_col{c}"
self.cellstyle_map[tuple(self.ctx[r, c])].append(f"row{r}_col{c}")
data.append(data_element)
body.append(index_headers + data)
return body
def _translate_latex(self, d: dict) -> None:
r"""
Post-process the default render dict for the LaTeX template format.
Processing items included are:
- Remove hidden columns from the non-headers part of the body.
- Place cellstyles directly in td cells rather than use cellstyle_map.
- Remove hidden indexes or reinsert missing th elements if part of multiindex
or multirow sparsification (so that \multirow and \multicol work correctly).
"""
d["head"] = [
[
{**col, "cellstyle": self.ctx_columns[r, c - self.index.nlevels]}
for c, col in enumerate(row)
if col["is_visible"]
]
for r, row in enumerate(d["head"])
]
body = []
for r, row in enumerate(d["body"]):
if all(self.hide_index_):
row_body_headers = []
else:
row_body_headers = [
{
**col,
"display_value": col["display_value"]
if col["is_visible"]
else "",
"cellstyle": self.ctx_index[r, c] if col["is_visible"] else [],
}
for c, col in enumerate(row)
if col["type"] == "th"
]
row_body_cells = [
{**col, "cellstyle": self.ctx[r, c - self.data.index.nlevels]}
for c, col in enumerate(row)
if (col["is_visible"] and col["type"] == "td")
]
body.append(row_body_headers + row_body_cells)
d["body"] = body
def format(
self,
formatter: ExtFormatter | None = None,
subset: Subset | None = None,
na_rep: str | None = None,
precision: int | None = None,
decimal: str = ".",
thousands: str | None = None,
escape: str | None = None,
) -> StylerRenderer:
r"""
Format the text display value of cells.
Parameters
----------
formatter : str, callable, dict or None
Object to define how values are displayed. See notes.
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.
na_rep : str, optional
Representation for missing values.
If ``na_rep`` is None, no special formatting is applied.
.. versionadded:: 1.0.0
precision : int, optional
Floating point precision to use for display purposes, if not determined by
the specified ``formatter``.
.. versionadded:: 1.3.0
decimal : str, default "."
Character used as decimal separator for floats, complex and integers
.. versionadded:: 1.3.0
thousands : str, optional, default None
Character used as thousands separator for floats, complex and integers
.. 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.
Escaping is done before ``formatter``.
.. versionadded:: 1.3.0
Returns
-------
self : Styler
Notes
-----
This method assigns a formatting function, ``formatter``, to each cell in the
DataFrame. If ``formatter`` is ``None``, then the default formatter is used.
If a callable then that function should take a data value as input and return
a displayable representation, such as a string. If ``formatter`` is
given as a string this is assumed to be a valid Python format specification
and is wrapped to a callable as ``string.format(x)``. If a ``dict`` is given,
keys should correspond to column names, and values should be string or
callable, as above.
The default formatter currently expresses floats and complex numbers with the
pandas display precision unless using the ``precision`` argument here. The
default formatter does not adjust the representation of missing values unless
the ``na_rep`` argument is used.
The ``subset`` argument defines which region to apply the formatting function
to. If the ``formatter`` argument is given in dict form but does not include
all columns within the subset then these columns will have the default formatter
applied. Any columns in the formatter dict excluded from the subset will
be ignored.
When using a ``formatter`` string the dtypes must be compatible, otherwise a
`ValueError` will be raised.
Examples
--------
Using ``na_rep`` and ``precision`` with the default ``formatter``
>>> df = pd.DataFrame([[np.nan, 1.0, 'A'], [2.0, np.nan, 3.0]])
>>> df.style.format(na_rep='MISS', precision=3) # doctest: +SKIP
0 1 2
0 MISS 1.000 A
1 2.000 MISS 3.000
Using a ``formatter`` specification on consistent column dtypes
>>> df.style.format('{:.2f}', na_rep='MISS', subset=[0,1]) # doctest: +SKIP
0 1 2
0 MISS 1.00 A
1 2.00 MISS 3.000000
Using the default ``formatter`` for unspecified columns
>>> df.style.format({0: '{:.2f}', 1: '£ {:.1f}'}, na_rep='MISS', precision=1)
... # doctest: +SKIP
0 1 2
0 MISS £ 1.0 A
1 2.00 MISS 3.0
Multiple ``na_rep`` or ``precision`` specifications under the default
``formatter``.
>>> df.style.format(na_rep='MISS', precision=1, subset=[0])
... .format(na_rep='PASS', precision=2, subset=[1, 2]) # doctest: +SKIP
0 1 2
0 MISS 1.00 A
1 2.0 PASS 3.00
Using a callable ``formatter`` function.
>>> func = lambda s: 'STRING' if isinstance(s, str) else 'FLOAT'
>>> df.style.format({0: '{:.1f}', 2: func}, precision=4, na_rep='MISS')
... # doctest: +SKIP
0 1 2
0 MISS 1.0000 STRING
1 2.0 MISS FLOAT
Using a ``formatter`` with HTML ``escape`` and ``na_rep``.
>>> df = pd.DataFrame([['<div></div>', '"A&B"', None]])
>>> s = df.style.format(
... '<a href="a.com/{0}">{0}</a>', escape="html", na_rep="NA"
... )
>>> s.to_html() # doctest: +SKIP
...
<td .. ><a href="a.com/<div></div>"><div></div></a></td>
<td .. ><a href="a.com/"A&B"">"A&B"</a></td>
<td .. >NA</td>
...
Using a ``formatter`` with LaTeX ``escape``.
>>> df = pd.DataFrame([["123"], ["~ ^"], ["$%#"]])
>>> df.style.format("\\textbf{{{}}}", escape="latex").to_latex()
... # doctest: +SKIP
\begin{tabular}{ll}
{} & {0} \\
0 & \textbf{123} \\
1 & \textbf{\textasciitilde \space \textasciicircum } \\
2 & \textbf{\$\%\#} \\
\end{tabular}
"""
if all(
(
formatter is None,
subset is None,
precision is None,
decimal == ".",
thousands is None,
na_rep is None,
escape is None,
)
):
self._display_funcs.clear()
return self # clear the formatter / revert to default and avoid looping
subset = slice(None) if subset is None else subset
subset = non_reducing_slice(subset)
data = self.data.loc[subset]
if not isinstance(formatter, dict):
formatter = {col: formatter for col in data.columns}
cis = self.columns.get_indexer_for(data.columns)
ris = self.index.get_indexer_for(data.index)
for ci in cis:
format_func = _maybe_wrap_formatter(
formatter.get(self.columns[ci]),
na_rep=na_rep,
precision=precision,
decimal=decimal,
thousands=thousands,
escape=escape,
)
for ri in ris:
self._display_funcs[(ri, ci)] = format_func
return self
def _element(
html_element: str,
html_class: str,
value: Any,
is_visible: bool,
**kwargs,
) -> dict:
"""
Template to return container with information for a <td></td> or <th></th> element.
"""
if "display_value" not in kwargs:
kwargs["display_value"] = value
return {
"type": html_element,
"value": value,
"class": html_class,
"is_visible": is_visible,
**kwargs,
}
def _get_trimming_maximums(rn, cn, max_elements, scaling_factor=0.8):
"""
Recursively reduce the number of rows and columns to satisfy max elements.
Parameters
----------
rn, cn : int
The number of input rows / columns
max_elements : int
The number of allowable elements
Returns
-------
rn, cn : tuple
New rn and cn values that satisfy the max_elements constraint
"""
def scale_down(rn, cn):
if cn >= rn:
return rn, int(cn * scaling_factor)
else:
return int(rn * scaling_factor), cn
while rn * cn > max_elements:
rn, cn = scale_down(rn, cn)
return rn, cn
def _get_level_lengths(
index: Index,
sparsify: bool,
max_index: int,
hidden_elements: Sequence[int] | None = None,
):
"""
Given an index, find the level length for each element.
Parameters
----------
index : Index
Index or columns to determine lengths of each element
sparsify : bool
Whether to hide or show each distinct element in a MultiIndex
max_index : int
The maximum number of elements to analyse along the index due to trimming
hidden_elements : sequence of int
Index positions of elements hidden from display in the index affecting
length
Returns
-------
Dict :
Result is a dictionary of (level, initial_position): span
"""
if isinstance(index, MultiIndex):
levels = index.format(sparsify=lib.no_default, adjoin=False)
else:
levels = index.format()
if hidden_elements is None:
hidden_elements = []
lengths = {}
if index.nlevels == 1:
for i, value in enumerate(levels):
if i not in hidden_elements:
lengths[(0, i)] = 1
return lengths
for i, lvl in enumerate(levels):
for j, row in enumerate(lvl):
if j >= max_index:
# stop the loop due to display trimming
break
if not sparsify:
lengths[(i, j)] = 1
elif (row is not lib.no_default) and (j not in hidden_elements):
last_label = j
lengths[(i, last_label)] = 1
elif row is not lib.no_default:
# even if its hidden, keep track of it in case
# length >1 and later elements are visible
last_label = j
lengths[(i, last_label)] = 0
elif j not in hidden_elements:
if lengths[(i, last_label)] == 0:
# if the previous iteration was first-of-kind but hidden then offset
last_label = j
lengths[(i, last_label)] = 1
else:
# else add to previous iteration
lengths[(i, last_label)] += 1
non_zero_lengths = {
element: length for element, length in lengths.items() if length >= 1
}
return non_zero_lengths
def _is_visible(idx_row, idx_col, lengths) -> bool:
"""
Index -> {(idx_row, idx_col): bool}).
"""
return (idx_col, idx_row) in lengths
def _format_table_styles(styles: CSSStyles) -> CSSStyles:
"""
looks for multiple CSS selectors and separates them:
[{'selector': 'td, th', 'props': 'a:v;'}]
---> [{'selector': 'td', 'props': 'a:v;'},
{'selector': 'th', 'props': 'a:v;'}]
"""
return [
{"selector": selector, "props": css_dict["props"]}
for css_dict in styles
for selector in css_dict["selector"].split(",")
]
def _default_formatter(x: Any, precision: int, thousands: bool = False) -> Any:
"""
Format the display of a value
Parameters
----------
x : Any
Input variable to be formatted
precision : Int
Floating point precision used if ``x`` is float or complex.
thousands : bool, default False
Whether to group digits with thousands separated with ",".
Returns
-------
value : Any
Matches input type, or string if input is float or complex or int with sep.
"""
if isinstance(x, (float, complex)):
if thousands:
return f"{x:,.{precision}f}"
return f"{x:.{precision}f}"
elif isinstance(x, int) and thousands:
return f"{x:,.0f}"
return x
def _wrap_decimal_thousands(
formatter: Callable, decimal: str, thousands: str | None
) -> Callable:
"""
Takes a string formatting function and wraps logic to deal with thousands and
decimal parameters, in the case that they are non-standard and that the input
is a (float, complex, int).
"""
def wrapper(x):
if isinstance(x, (float, complex, int)):
if decimal != "." and thousands is not None and thousands != ",":
return (
formatter(x)
.replace(",", "§_§-") # rare string to avoid "," <-> "." clash.
.replace(".", decimal)
.replace("§_§-", thousands)
)
elif decimal != "." and (thousands is None or thousands == ","):
return formatter(x).replace(".", decimal)
elif decimal == "." and thousands is not None and thousands != ",":
return formatter(x).replace(",", thousands)
return formatter(x)
return wrapper
def _str_escape(x, escape):
"""if escaping: only use on str, else return input"""
if isinstance(x, str):
if escape == "html":
return escape_html(x)
elif escape == "latex":
return _escape_latex(x)
else:
raise ValueError(