forked from pandas-dev/pandas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstyle_render.py
2342 lines (2023 loc) · 83.7 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._typing import (
Axis,
Level,
)
from pandas.compat._optional import import_optional_dependency
from pandas.core.dtypes.common import (
is_complex,
is_float,
is_integer,
)
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
tinycss2 = import_optional_dependency("tinycss2")
BaseFormatter = Union[str, Callable]
ExtFormatter = Union[BaseFormatter, Dict[Any, Optional[BaseFormatter]]]
CSSPair = Tuple[str, Union[str, 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")
template_string = env.get_template("string.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,
precision: int | None = None,
) -> None:
# 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 = uuid or uuid4().hex[: min(32, uuid_len)]
self.uuid_len = len(self.uuid)
self.table_styles = table_styles
self.table_attributes = table_attributes
self.caption = caption
self.cell_ids = cell_ids
self.css = {
"row_heading": "row_heading",
"col_heading": "col_heading",
"index_name": "index_name",
"col": "col",
"row": "row",
"col_trim": "col_trim",
"row_trim": "row_trim",
"level": "level",
"data": "data",
"blank": "blank",
"foot": "foot",
}
self.concatenated: StylerRenderer | None = None
# add rendering variables
self.hide_index_names: bool = False
self.hide_column_names: bool = False
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
precision = (
get_option("styler.format.precision") if precision is None else precision
)
self._display_funcs: DefaultDict[ # maps (row, col) -> format func
tuple[int, int], Callable[[Any], str]
] = defaultdict(lambda: partial(_default_formatter, precision=precision))
self._display_funcs_index: DefaultDict[ # maps (row, level) -> format func
tuple[int, int], Callable[[Any], str]
] = defaultdict(lambda: partial(_default_formatter, precision=precision))
self._display_funcs_columns: DefaultDict[ # maps (level, col) -> format func
tuple[int, int], Callable[[Any], str]
] = defaultdict(lambda: partial(_default_formatter, precision=precision))
def _render(
self,
sparse_index: bool,
sparse_columns: bool,
max_rows: int | None = None,
max_cols: int | None = None,
blank: str = "",
):
"""
Computes and applies styles and then generates the general render dicts.
Also extends the `ctx` and `ctx_index` attributes with those of concatenated
stylers for use within `_translate_latex`
"""
self._compute()
dx = None
if self.concatenated is not None:
self.concatenated.hide_index_ = self.hide_index_
self.concatenated.hidden_columns = self.hidden_columns
self.concatenated.css = {
**self.css,
"data": f"{self.css['foot']}_{self.css['data']}",
"row_heading": f"{self.css['foot']}_{self.css['row_heading']}",
"row": f"{self.css['foot']}_{self.css['row']}",
"foot": self.css["foot"],
}
dx = self.concatenated._render(
sparse_index, sparse_columns, max_rows, max_cols, blank
)
for (r, c), v in self.concatenated.ctx.items():
self.ctx[(r + len(self.index), c)] = v
for (r, c), v in self.concatenated.ctx_index.items():
self.ctx_index[(r + len(self.index), c)] = v
d = self._translate(sparse_index, sparse_columns, max_rows, max_cols, blank, dx)
return d
def _render_html(
self,
sparse_index: bool,
sparse_columns: bool,
max_rows: int | None = None,
max_cols: int | None = None,
**kwargs,
) -> str:
"""
Renders the ``Styler`` including all applied styles to HTML.
Generates a dict with necessary kwargs passed to jinja2 template.
"""
d = self._render(sparse_index, sparse_columns, max_rows, max_cols, " ")
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, clines: str | None, **kwargs
) -> str:
"""
Render a Styler in latex format
"""
d = self._render(sparse_index, sparse_columns, None, None)
self._translate_latex(d, clines=clines)
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 _render_string(
self,
sparse_index: bool,
sparse_columns: bool,
max_rows: int | None = None,
max_cols: int | None = None,
**kwargs,
) -> str:
"""
Render a Styler in string format
"""
d = self._render(sparse_index, sparse_columns, max_rows, max_cols)
d.update(kwargs)
return self.template_string.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,
max_rows: int | None = None,
max_cols: int | None = None,
blank: str = " ",
dx: dict | None = None,
):
"""
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`.
max_rows, max_cols : int, optional
Specific max rows and cols. max_elements always take precedence in render.
blank : str
Entry to top-left blank cells.
dx : dict
The render dict of the concatenated Styler.
Returns
-------
d : dict
The following structure: {uuid, table_styles, caption, head, body,
cellstyle, table_attributes}
"""
self.css["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_rows if max_rows else get_option("styler.render.max_rows")
max_cols = max_cols if max_cols else get_option("styler.render.max_columns")
max_rows, max_cols = _get_trimming_maximums(
len(self.data.index),
len(self.data.columns),
max_elements,
max_rows,
max_cols,
)
self.cellstyle_map_columns: DefaultDict[
tuple[CSSPair, ...], list[str]
] = defaultdict(list)
head = self._translate_header(sparse_cols, max_cols)
d.update({"head": head})
# for sparsifying a MultiIndex and for use with latex clines
idx_lengths = _get_level_lengths(
self.index, sparse_index, max_rows, self.hidden_rows
)
d.update({"index_lengths": idx_lengths})
self.cellstyle_map: DefaultDict[tuple[CSSPair, ...], list[str]] = defaultdict(
list
)
self.cellstyle_map_index: DefaultDict[
tuple[CSSPair, ...], list[str]
] = defaultdict(list)
body: list = self._translate_body(idx_lengths, max_rows, max_cols)
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})
if dx is not None: # self.concatenated is not None
d["body"].extend(dx["body"]) # type: ignore[union-attr]
d["cellstyle"].extend(dx["cellstyle"]) # type: ignore[union-attr]
d["cellstyle_index"].extend(dx["cellstyle"]) # type: ignore[union-attr]
table_attr = self.table_attributes
if not get_option("styler.html.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, d)
return d
def _translate_header(self, sparsify_cols: bool, max_cols: int):
"""
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
----------
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.
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()
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 or not clabels:
continue
else:
header_row = self._generate_col_header_row(
(r, clabels), max_cols, col_lengths
)
head.append(header_row)
# 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 self.hide_index_names
):
index_names_row = self._generate_index_names_row(
clabels, max_cols, col_lengths
)
head.append(index_names_row)
return head
def _generate_col_header_row(self, iter: tuple, max_cols: int, col_lengths: dict):
"""
Generate the row containing column headers:
+----------------------------+---------------+---------------------------+
| index_blanks ... | column_name_i | column_headers (level_i) |
+----------------------------+---------------+---------------------------+
Parameters
----------
iter : tuple
Looping variables from outer scope
max_cols : int
Permissible number of columns
col_lengths :
c
Returns
-------
list of elements
"""
r, clabels = iter
# number of index blanks is governed by number of hidden index levels
index_blanks = [
_element("th", self.css["blank"], self.css["blank_value"], True)
] * (self.index.nlevels - sum(self.hide_index_) - 1)
name = self.data.columns.names[r]
column_name = [
_element(
"th",
(
f"{self.css['blank']} {self.css['level']}{r}"
if name is None
else f"{self.css['index_name']} {self.css['level']}{r}"
),
name
if (name is not None and not self.hide_column_names)
else self.css["blank_value"],
not all(self.hide_index_),
)
]
column_headers: list = []
visible_col_count: int = 0
for c, value in enumerate(clabels[r]):
header_element_visible = _is_visible(c, r, col_lengths)
if header_element_visible:
visible_col_count += col_lengths.get((r, c), 0)
if self._check_trim(
visible_col_count,
max_cols,
column_headers,
"th",
f"{self.css['col_heading']} {self.css['level']}{r} "
f"{self.css['col_trim']}",
):
break
header_element = _element(
"th",
(
f"{self.css['col_heading']} {self.css['level']}{r} "
f"{self.css['col']}{c}"
),
value,
header_element_visible,
display_value=self._display_funcs_columns[(r, c)](value),
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"{self.css['level']}{r}_{self.css['col']}{c}"
if (
header_element_visible
and (r, c) in self.ctx_columns
and self.ctx_columns[r, c]
):
header_element["id"] = f"{self.css['level']}{r}_{self.css['col']}{c}"
self.cellstyle_map_columns[tuple(self.ctx_columns[r, c])].append(
f"{self.css['level']}{r}_{self.css['col']}{c}"
)
column_headers.append(header_element)
return index_blanks + column_name + column_headers
def _generate_index_names_row(self, iter: tuple, max_cols: int, col_lengths: dict):
"""
Generate the row containing index names
+----------------------------+---------------+---------------------------+
| index_names (level_0 to level_n) ... | column_blanks ... |
+----------------------------+---------------+---------------------------+
Parameters
----------
iter : tuple
Looping variables from outer scope
max_cols : int
Permissible number of columns
Returns
-------
list of elements
"""
clabels = iter
index_names = [
_element(
"th",
f"{self.css['index_name']} {self.css['level']}{c}",
self.css["blank_value"] if name is None else name,
not self.hide_index_[c],
)
for c, name in enumerate(self.data.index.names)
]
column_blanks: list = []
visible_col_count: int = 0
if clabels:
last_level = self.columns.nlevels - 1 # use last level since never sparsed
for c, value in enumerate(clabels[last_level]):
header_element_visible = _is_visible(c, last_level, col_lengths)
if header_element_visible:
visible_col_count += 1
if self._check_trim(
visible_col_count,
max_cols,
column_blanks,
"th",
f"{self.css['blank']} {self.css['col']}{c} {self.css['col_trim']}",
self.css["blank_value"],
):
break
column_blanks.append(
_element(
"th",
f"{self.css['blank']} {self.css['col']}{c}",
self.css["blank_value"],
c not in self.hidden_columns,
)
)
return index_names + column_blanks
def _translate_body(self, idx_lengths: dict, max_rows: int, max_cols: int):
"""
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
----------
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.
"""
rlabels = self.data.index.tolist()
if not isinstance(self.data.index, MultiIndex):
rlabels = [[x] for x in rlabels]
body: list = []
visible_row_count: int = 0
for r, row_tup in [
z for z in enumerate(self.data.itertuples()) if z[0] not in self.hidden_rows
]:
visible_row_count += 1
if self._check_trim(
visible_row_count,
max_rows,
body,
"row",
):
break
body_row = self._generate_body_row(
(r, row_tup, rlabels), max_cols, idx_lengths
)
body.append(body_row)
return body
def _check_trim(
self,
count: int,
max: int,
obj: list,
element: str,
css: str | None = None,
value: str = "...",
) -> bool:
"""
Indicates whether to break render loops and append a trimming indicator
Parameters
----------
count : int
The loop count of previous visible items.
max : int
The allowable rendered items in the loop.
obj : list
The current render collection of the rendered items.
element : str
The type of element to append in the case a trimming indicator is needed.
css : str, optional
The css to add to the trimming indicator element.
value : str, optional
The value of the elements display if necessary.
Returns
-------
result : bool
Whether a trimming element was required and appended.
"""
if count > max:
if element == "row":
obj.append(self._generate_trimmed_row(max))
else:
obj.append(_element(element, css, value, True, attributes=""))
return True
return False
def _generate_trimmed_row(self, max_cols: int) -> list:
"""
When a render has too many rows we generate a trimming row containing "..."
Parameters
----------
max_cols : int
Number of permissible columns
Returns
-------
list of elements
"""
index_headers = [
_element(
"th",
(
f"{self.css['row_heading']} {self.css['level']}{c} "
f"{self.css['row_trim']}"
),
"...",
not self.hide_index_[c],
attributes="",
)
for c in range(self.data.index.nlevels)
]
data: list = []
visible_col_count: int = 0
for c, _ in enumerate(self.columns):
data_element_visible = c not in self.hidden_columns
if data_element_visible:
visible_col_count += 1
if self._check_trim(
visible_col_count,
max_cols,
data,
"td",
f"{self.css['data']} {self.css['row_trim']} {self.css['col_trim']}",
):
break
data.append(
_element(
"td",
f"{self.css['data']} {self.css['col']}{c} {self.css['row_trim']}",
"...",
data_element_visible,
attributes="",
)
)
return index_headers + data
def _generate_body_row(
self,
iter: tuple,
max_cols: int,
idx_lengths: dict,
):
"""
Generate a regular row for the body section of appropriate format.
+--------------------------------------------+---------------------------+
| index_header_0 ... index_header_n | data_by_column ... |
+--------------------------------------------+---------------------------+
Parameters
----------
iter : tuple
Iterable from outer scope: row number, row data tuple, row index labels.
max_cols : int
Number of permissible columns.
idx_lengths : dict
A map of the sparsification structure of the index
Returns
-------
list of elements
"""
r, row_tup, rlabels = iter
index_headers = []
for c, value in enumerate(rlabels[r]):
header_element_visible = (
_is_visible(r, c, idx_lengths) and not self.hide_index_[c]
)
header_element = _element(
"th",
(
f"{self.css['row_heading']} {self.css['level']}{c} "
f"{self.css['row']}{r}"
),
value,
header_element_visible,
display_value=self._display_funcs_index[(r, c)](value),
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"{self.css['level']}{c}_{self.css['row']}{r}" # id is given
if (
header_element_visible
and (r, c) in self.ctx_index
and self.ctx_index[r, c]
):
# always add id if a style is specified
header_element["id"] = f"{self.css['level']}{c}_{self.css['row']}{r}"
self.cellstyle_map_index[tuple(self.ctx_index[r, c])].append(
f"{self.css['level']}{c}_{self.css['row']}{r}"
)
index_headers.append(header_element)
data: list = []
visible_col_count: int = 0
for c, value in enumerate(row_tup[1:]):
data_element_visible = (
c not in self.hidden_columns and r not in self.hidden_rows
)
if data_element_visible:
visible_col_count += 1
if self._check_trim(
visible_col_count,
max_cols,
data,
"td",
f"{self.css['data']} {self.css['row']}{r} {self.css['col_trim']}",
):
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"{self.css['data']} {self.css['row']}{r} "
f"{self.css['col']}{c}{cls}"
),
value,
data_element_visible,
attributes="",
display_value=self._display_funcs[(r, c)](value),
)
if self.cell_ids:
data_element["id"] = f"{self.css['row']}{r}_{self.css['col']}{c}"
if data_element_visible and (r, c) in self.ctx and self.ctx[r, c]:
# always add id if needed due to specified style
data_element["id"] = f"{self.css['row']}{r}_{self.css['col']}{c}"
self.cellstyle_map[tuple(self.ctx[r, c])].append(
f"{self.css['row']}{r}_{self.css['col']}{c}"
)
data.append(data_element)
return index_headers + data
def _translate_latex(self, d: dict, clines: str | None) -> 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).
"""
index_levels = self.index.nlevels
visible_index_level_n = index_levels - sum(self.hide_index_)
d["head"] = [
[
{**col, "cellstyle": self.ctx_columns[r, c - visible_index_level_n]}
for c, col in enumerate(row)
if col["is_visible"]
]
for r, row in enumerate(d["head"])
]
def concatenated_visible_rows(obj, n, row_indices):
"""
Extract all visible row indices recursively from concatenated stylers.
"""
row_indices.extend(
[r + n for r in range(len(obj.index)) if r not in obj.hidden_rows]
)
return (
row_indices
if obj.concatenated is None
else concatenated_visible_rows(
obj.concatenated, n + len(obj.index), row_indices
)
)
body = []
for r, row in zip(concatenated_visible_rows(self, 0, []), d["body"]):
# note: cannot enumerate d["body"] because rows were dropped if hidden
# during _translate_body so must zip to acquire the true r-index associated
# with the ctx obj which contains the cell styles.
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],
}
for c, col in enumerate(row[:index_levels])
if (col["type"] == "th" and not self.hide_index_[c])
]
row_body_cells = [
{**col, "cellstyle": self.ctx[r, c]}
for c, col in enumerate(row[index_levels:])
if (col["is_visible"] and col["type"] == "td")
]
body.append(row_body_headers + row_body_cells)
d["body"] = body
# clines are determined from info on index_lengths and hidden_rows and input
# to a dict defining which row clines should be added in the template.
if clines not in [
None,
"all;data",
"all;index",
"skip-last;data",
"skip-last;index",
]:
raise ValueError(
f"`clines` value of {clines} is invalid. Should either be None or one "
f"of 'all;data', 'all;index', 'skip-last;data', 'skip-last;index'."
)
elif clines is not None:
data_len = len(row_body_cells) if "data" in clines and d["body"] else 0
d["clines"] = defaultdict(list)
visible_row_indexes: list[int] = [
r for r in range(len(self.data.index)) if r not in self.hidden_rows
]
visible_index_levels: list[int] = [
i for i in range(index_levels) if not self.hide_index_[i]
]
for rn, r in enumerate(visible_row_indexes):
for lvln, lvl in enumerate(visible_index_levels):
if lvl == index_levels - 1 and "skip-last" in clines:
continue
idx_len = d["index_lengths"].get((lvl, r), None)
if idx_len is not None: # i.e. not a sparsified entry
d["clines"][rn + idx_len].append(
f"\\cline{{{lvln+1}-{len(visible_index_levels)+data_len}}}"
)
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,
hyperlinks: 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
hyperlinks : {"html", "latex"}, optional
Convert string patterns containing https://, http://, ftp:// or www. to
HTML <a> tags as clickable URL hyperlinks if "html", or LaTeX \href
commands if "latex".
.. versionadded:: 1.4.0
Returns
-------
self : Styler
See Also
--------
Styler.format_index: Format the text display value of index labels.
Notes
-----
This method assigns a formatting function, ``formatter``, to each cell in the