applied-ai-018 commited on
Commit
bac2ee3
Β·
verified Β·
1 Parent(s): 985634b

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes. Β  See raw diff
Files changed (50) hide show
  1. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/excel/__pycache__/__init__.cpython-310.pyc +0 -0
  2. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/excel/__pycache__/test_odf.cpython-310.pyc +0 -0
  3. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/excel/__pycache__/test_odswriter.cpython-310.pyc +0 -0
  4. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/excel/__pycache__/test_openpyxl.cpython-310.pyc +0 -0
  5. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/excel/__pycache__/test_readers.cpython-310.pyc +0 -0
  6. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/excel/__pycache__/test_style.cpython-310.pyc +0 -0
  7. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/excel/__pycache__/test_writers.cpython-310.pyc +0 -0
  8. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/excel/__pycache__/test_xlrd.cpython-310.pyc +0 -0
  9. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/excel/__pycache__/test_xlsxwriter.cpython-310.pyc +0 -0
  10. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/excel/test_style.py +298 -0
  11. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/__init__.cpython-310.pyc +0 -0
  12. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_console.cpython-310.pyc +0 -0
  13. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_css.cpython-310.pyc +0 -0
  14. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_eng_formatting.cpython-310.pyc +0 -0
  15. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_format.cpython-310.pyc +0 -0
  16. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_ipython_compat.cpython-310.pyc +0 -0
  17. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_printing.cpython-310.pyc +0 -0
  18. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_to_csv.cpython-310.pyc +0 -0
  19. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_to_excel.cpython-310.pyc +0 -0
  20. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_to_html.cpython-310.pyc +0 -0
  21. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_to_latex.cpython-310.pyc +0 -0
  22. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_to_markdown.cpython-310.pyc +0 -0
  23. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_to_string.cpython-310.pyc +0 -0
  24. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/__init__.py +0 -0
  25. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/__init__.cpython-310.pyc +0 -0
  26. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_bar.cpython-310.pyc +0 -0
  27. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_exceptions.cpython-310.pyc +0 -0
  28. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_format.cpython-310.pyc +0 -0
  29. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_html.cpython-310.pyc +0 -0
  30. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_matplotlib.cpython-310.pyc +0 -0
  31. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_non_unique.cpython-310.pyc +0 -0
  32. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_style.cpython-310.pyc +0 -0
  33. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_to_string.cpython-310.pyc +0 -0
  34. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_tooltip.cpython-310.pyc +0 -0
  35. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/test_bar.py +358 -0
  36. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/test_exceptions.py +44 -0
  37. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/test_format.py +562 -0
  38. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/test_highlight.py +218 -0
  39. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/test_html.py +1009 -0
  40. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/test_matplotlib.py +335 -0
  41. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/test_non_unique.py +140 -0
  42. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/test_style.py +1588 -0
  43. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/test_to_latex.py +1090 -0
  44. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/test_to_string.py +96 -0
  45. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/test_tooltip.py +85 -0
  46. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/test_console.py +72 -0
  47. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/test_eng_formatting.py +254 -0
  48. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/test_format.py +2293 -0
  49. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/test_ipython_compat.py +90 -0
  50. llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/test_printing.py +129 -0
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/excel/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (194 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/excel/__pycache__/test_odf.cpython-310.pyc ADDED
Binary file (2.35 kB). View file
 
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/excel/__pycache__/test_odswriter.cpython-310.pyc ADDED
Binary file (3.34 kB). View file
 
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/excel/__pycache__/test_openpyxl.cpython-310.pyc ADDED
Binary file (12.4 kB). View file
 
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/excel/__pycache__/test_readers.cpython-310.pyc ADDED
Binary file (48.8 kB). View file
 
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/excel/__pycache__/test_style.cpython-310.pyc ADDED
Binary file (8.72 kB). View file
 
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/excel/__pycache__/test_writers.cpython-310.pyc ADDED
Binary file (46.1 kB). View file
 
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/excel/__pycache__/test_xlrd.cpython-310.pyc ADDED
Binary file (2.35 kB). View file
 
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/excel/__pycache__/test_xlsxwriter.cpython-310.pyc ADDED
Binary file (2.75 kB). View file
 
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/excel/test_style.py ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import time
3
+
4
+ import numpy as np
5
+ import pytest
6
+
7
+ from pandas.compat import is_platform_windows
8
+ import pandas.util._test_decorators as td
9
+
10
+ from pandas import (
11
+ DataFrame,
12
+ read_excel,
13
+ )
14
+ import pandas._testing as tm
15
+
16
+ from pandas.io.excel import ExcelWriter
17
+ from pandas.io.formats.excel import ExcelFormatter
18
+
19
+ pytest.importorskip("jinja2")
20
+ # jinja2 is currently required for Styler.__init__(). Technically Styler.to_excel
21
+ # could compute styles and render to excel without jinja2, since there is no
22
+ # 'template' file, but this needs the import error to delayed until render time.
23
+
24
+ if is_platform_windows():
25
+ pytestmark = pytest.mark.single_cpu
26
+
27
+
28
+ def assert_equal_cell_styles(cell1, cell2):
29
+ # TODO: should find a better way to check equality
30
+ assert cell1.alignment.__dict__ == cell2.alignment.__dict__
31
+ assert cell1.border.__dict__ == cell2.border.__dict__
32
+ assert cell1.fill.__dict__ == cell2.fill.__dict__
33
+ assert cell1.font.__dict__ == cell2.font.__dict__
34
+ assert cell1.number_format == cell2.number_format
35
+ assert cell1.protection.__dict__ == cell2.protection.__dict__
36
+
37
+
38
+ @pytest.mark.parametrize(
39
+ "engine",
40
+ ["xlsxwriter", "openpyxl"],
41
+ )
42
+ def test_styler_to_excel_unstyled(engine):
43
+ # compare DataFrame.to_excel and Styler.to_excel when no styles applied
44
+ pytest.importorskip(engine)
45
+ df = DataFrame(np.random.default_rng(2).standard_normal((2, 2)))
46
+ with tm.ensure_clean(".xlsx") as path:
47
+ with ExcelWriter(path, engine=engine) as writer:
48
+ df.to_excel(writer, sheet_name="dataframe")
49
+ df.style.to_excel(writer, sheet_name="unstyled")
50
+
51
+ openpyxl = pytest.importorskip("openpyxl") # test loading only with openpyxl
52
+ with contextlib.closing(openpyxl.load_workbook(path)) as wb:
53
+ for col1, col2 in zip(wb["dataframe"].columns, wb["unstyled"].columns):
54
+ assert len(col1) == len(col2)
55
+ for cell1, cell2 in zip(col1, col2):
56
+ assert cell1.value == cell2.value
57
+ assert_equal_cell_styles(cell1, cell2)
58
+
59
+
60
+ shared_style_params = [
61
+ (
62
+ "background-color: #111222",
63
+ ["fill", "fgColor", "rgb"],
64
+ {"xlsxwriter": "FF111222", "openpyxl": "00111222"},
65
+ ),
66
+ (
67
+ "color: #111222",
68
+ ["font", "color", "value"],
69
+ {"xlsxwriter": "FF111222", "openpyxl": "00111222"},
70
+ ),
71
+ ("font-family: Arial;", ["font", "name"], "arial"),
72
+ ("font-weight: bold;", ["font", "b"], True),
73
+ ("font-style: italic;", ["font", "i"], True),
74
+ ("text-decoration: underline;", ["font", "u"], "single"),
75
+ ("number-format: $??,???.00;", ["number_format"], "$??,???.00"),
76
+ ("text-align: left;", ["alignment", "horizontal"], "left"),
77
+ (
78
+ "vertical-align: bottom;",
79
+ ["alignment", "vertical"],
80
+ {"xlsxwriter": None, "openpyxl": "bottom"}, # xlsxwriter Fails
81
+ ),
82
+ ("vertical-align: middle;", ["alignment", "vertical"], "center"),
83
+ # Border widths
84
+ ("border-left: 2pt solid red", ["border", "left", "style"], "medium"),
85
+ ("border-left: 1pt dotted red", ["border", "left", "style"], "dotted"),
86
+ ("border-left: 2pt dotted red", ["border", "left", "style"], "mediumDashDotDot"),
87
+ ("border-left: 1pt dashed red", ["border", "left", "style"], "dashed"),
88
+ ("border-left: 2pt dashed red", ["border", "left", "style"], "mediumDashed"),
89
+ ("border-left: 1pt solid red", ["border", "left", "style"], "thin"),
90
+ ("border-left: 3pt solid red", ["border", "left", "style"], "thick"),
91
+ # Border expansion
92
+ (
93
+ "border-left: 2pt solid #111222",
94
+ ["border", "left", "color", "rgb"],
95
+ {"xlsxwriter": "FF111222", "openpyxl": "00111222"},
96
+ ),
97
+ ("border: 1pt solid red", ["border", "top", "style"], "thin"),
98
+ (
99
+ "border: 1pt solid #111222",
100
+ ["border", "top", "color", "rgb"],
101
+ {"xlsxwriter": "FF111222", "openpyxl": "00111222"},
102
+ ),
103
+ ("border: 1pt solid red", ["border", "right", "style"], "thin"),
104
+ (
105
+ "border: 1pt solid #111222",
106
+ ["border", "right", "color", "rgb"],
107
+ {"xlsxwriter": "FF111222", "openpyxl": "00111222"},
108
+ ),
109
+ ("border: 1pt solid red", ["border", "bottom", "style"], "thin"),
110
+ (
111
+ "border: 1pt solid #111222",
112
+ ["border", "bottom", "color", "rgb"],
113
+ {"xlsxwriter": "FF111222", "openpyxl": "00111222"},
114
+ ),
115
+ ("border: 1pt solid red", ["border", "left", "style"], "thin"),
116
+ (
117
+ "border: 1pt solid #111222",
118
+ ["border", "left", "color", "rgb"],
119
+ {"xlsxwriter": "FF111222", "openpyxl": "00111222"},
120
+ ),
121
+ # Border styles
122
+ (
123
+ "border-left-style: hair; border-left-color: black",
124
+ ["border", "left", "style"],
125
+ "hair",
126
+ ),
127
+ ]
128
+
129
+
130
+ @pytest.mark.parametrize(
131
+ "engine",
132
+ ["xlsxwriter", "openpyxl"],
133
+ )
134
+ @pytest.mark.parametrize("css, attrs, expected", shared_style_params)
135
+ def test_styler_to_excel_basic(engine, css, attrs, expected):
136
+ pytest.importorskip(engine)
137
+ df = DataFrame(np.random.default_rng(2).standard_normal((1, 1)))
138
+ styler = df.style.map(lambda x: css)
139
+
140
+ with tm.ensure_clean(".xlsx") as path:
141
+ with ExcelWriter(path, engine=engine) as writer:
142
+ df.to_excel(writer, sheet_name="dataframe")
143
+ styler.to_excel(writer, sheet_name="styled")
144
+
145
+ openpyxl = pytest.importorskip("openpyxl") # test loading only with openpyxl
146
+ with contextlib.closing(openpyxl.load_workbook(path)) as wb:
147
+ # test unstyled data cell does not have expected styles
148
+ # test styled cell has expected styles
149
+ u_cell, s_cell = wb["dataframe"].cell(2, 2), wb["styled"].cell(2, 2)
150
+ for attr in attrs:
151
+ u_cell, s_cell = getattr(u_cell, attr, None), getattr(s_cell, attr)
152
+
153
+ if isinstance(expected, dict):
154
+ assert u_cell is None or u_cell != expected[engine]
155
+ assert s_cell == expected[engine]
156
+ else:
157
+ assert u_cell is None or u_cell != expected
158
+ assert s_cell == expected
159
+
160
+
161
+ @pytest.mark.parametrize(
162
+ "engine",
163
+ ["xlsxwriter", "openpyxl"],
164
+ )
165
+ @pytest.mark.parametrize("css, attrs, expected", shared_style_params)
166
+ def test_styler_to_excel_basic_indexes(engine, css, attrs, expected):
167
+ pytest.importorskip(engine)
168
+ df = DataFrame(np.random.default_rng(2).standard_normal((1, 1)))
169
+
170
+ styler = df.style
171
+ styler.map_index(lambda x: css, axis=0)
172
+ styler.map_index(lambda x: css, axis=1)
173
+
174
+ null_styler = df.style
175
+ null_styler.map(lambda x: "null: css;")
176
+ null_styler.map_index(lambda x: "null: css;", axis=0)
177
+ null_styler.map_index(lambda x: "null: css;", axis=1)
178
+
179
+ with tm.ensure_clean(".xlsx") as path:
180
+ with ExcelWriter(path, engine=engine) as writer:
181
+ null_styler.to_excel(writer, sheet_name="null_styled")
182
+ styler.to_excel(writer, sheet_name="styled")
183
+
184
+ openpyxl = pytest.importorskip("openpyxl") # test loading only with openpyxl
185
+ with contextlib.closing(openpyxl.load_workbook(path)) as wb:
186
+ # test null styled index cells does not have expected styles
187
+ # test styled cell has expected styles
188
+ ui_cell, si_cell = wb["null_styled"].cell(2, 1), wb["styled"].cell(2, 1)
189
+ uc_cell, sc_cell = wb["null_styled"].cell(1, 2), wb["styled"].cell(1, 2)
190
+ for attr in attrs:
191
+ ui_cell, si_cell = getattr(ui_cell, attr, None), getattr(si_cell, attr)
192
+ uc_cell, sc_cell = getattr(uc_cell, attr, None), getattr(sc_cell, attr)
193
+
194
+ if isinstance(expected, dict):
195
+ assert ui_cell is None or ui_cell != expected[engine]
196
+ assert si_cell == expected[engine]
197
+ assert uc_cell is None or uc_cell != expected[engine]
198
+ assert sc_cell == expected[engine]
199
+ else:
200
+ assert ui_cell is None or ui_cell != expected
201
+ assert si_cell == expected
202
+ assert uc_cell is None or uc_cell != expected
203
+ assert sc_cell == expected
204
+
205
+
206
+ # From https://openpyxl.readthedocs.io/en/stable/api/openpyxl.styles.borders.html
207
+ # Note: Leaving behavior of "width"-type styles undefined; user should use border-width
208
+ # instead
209
+ excel_border_styles = [
210
+ # "thin",
211
+ "dashed",
212
+ "mediumDashDot",
213
+ "dashDotDot",
214
+ "hair",
215
+ "dotted",
216
+ "mediumDashDotDot",
217
+ # "medium",
218
+ "double",
219
+ "dashDot",
220
+ "slantDashDot",
221
+ # "thick",
222
+ "mediumDashed",
223
+ ]
224
+
225
+
226
+ @pytest.mark.parametrize(
227
+ "engine",
228
+ ["xlsxwriter", "openpyxl"],
229
+ )
230
+ @pytest.mark.parametrize("border_style", excel_border_styles)
231
+ def test_styler_to_excel_border_style(engine, border_style):
232
+ css = f"border-left: {border_style} black thin"
233
+ attrs = ["border", "left", "style"]
234
+ expected = border_style
235
+
236
+ pytest.importorskip(engine)
237
+ df = DataFrame(np.random.default_rng(2).standard_normal((1, 1)))
238
+ styler = df.style.map(lambda x: css)
239
+
240
+ with tm.ensure_clean(".xlsx") as path:
241
+ with ExcelWriter(path, engine=engine) as writer:
242
+ df.to_excel(writer, sheet_name="dataframe")
243
+ styler.to_excel(writer, sheet_name="styled")
244
+
245
+ openpyxl = pytest.importorskip("openpyxl") # test loading only with openpyxl
246
+ with contextlib.closing(openpyxl.load_workbook(path)) as wb:
247
+ # test unstyled data cell does not have expected styles
248
+ # test styled cell has expected styles
249
+ u_cell, s_cell = wb["dataframe"].cell(2, 2), wb["styled"].cell(2, 2)
250
+ for attr in attrs:
251
+ u_cell, s_cell = getattr(u_cell, attr, None), getattr(s_cell, attr)
252
+
253
+ if isinstance(expected, dict):
254
+ assert u_cell is None or u_cell != expected[engine]
255
+ assert s_cell == expected[engine]
256
+ else:
257
+ assert u_cell is None or u_cell != expected
258
+ assert s_cell == expected
259
+
260
+
261
+ def test_styler_custom_converter():
262
+ openpyxl = pytest.importorskip("openpyxl")
263
+
264
+ def custom_converter(css):
265
+ return {"font": {"color": {"rgb": "111222"}}}
266
+
267
+ df = DataFrame(np.random.default_rng(2).standard_normal((1, 1)))
268
+ styler = df.style.map(lambda x: "color: #888999")
269
+ with tm.ensure_clean(".xlsx") as path:
270
+ with ExcelWriter(path, engine="openpyxl") as writer:
271
+ ExcelFormatter(styler, style_converter=custom_converter).write(
272
+ writer, sheet_name="custom"
273
+ )
274
+
275
+ with contextlib.closing(openpyxl.load_workbook(path)) as wb:
276
+ assert wb["custom"].cell(2, 2).font.color.value == "00111222"
277
+
278
+
279
+ @pytest.mark.single_cpu
280
+ @td.skip_if_not_us_locale
281
+ def test_styler_to_s3(s3_public_bucket, s3so):
282
+ # GH#46381
283
+
284
+ mock_bucket_name, target_file = s3_public_bucket.name, "test.xlsx"
285
+ df = DataFrame({"x": [1, 2, 3], "y": [2, 4, 6]})
286
+ styler = df.style.set_sticky(axis="index")
287
+ styler.to_excel(f"s3://{mock_bucket_name}/{target_file}", storage_options=s3so)
288
+ timeout = 5
289
+ while True:
290
+ if target_file in (obj.key for obj in s3_public_bucket.objects.all()):
291
+ break
292
+ time.sleep(0.1)
293
+ timeout -= 0.1
294
+ assert timeout > 0, "Timed out waiting for file to appear on moto"
295
+ result = read_excel(
296
+ f"s3://{mock_bucket_name}/{target_file}", index_col=0, storage_options=s3so
297
+ )
298
+ tm.assert_frame_equal(result, df)
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (196 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_console.cpython-310.pyc ADDED
Binary file (2.82 kB). View file
 
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_css.cpython-310.pyc ADDED
Binary file (6.35 kB). View file
 
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_eng_formatting.cpython-310.pyc ADDED
Binary file (7.87 kB). View file
 
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_format.cpython-310.pyc ADDED
Binary file (65.4 kB). View file
 
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_ipython_compat.cpython-310.pyc ADDED
Binary file (2.98 kB). View file
 
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_printing.cpython-310.pyc ADDED
Binary file (4.77 kB). View file
 
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_to_csv.cpython-310.pyc ADDED
Binary file (22.4 kB). View file
 
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_to_excel.cpython-310.pyc ADDED
Binary file (10.7 kB). View file
 
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_to_html.cpython-310.pyc ADDED
Binary file (35.5 kB). View file
 
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_to_latex.cpython-310.pyc ADDED
Binary file (44 kB). View file
 
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_to_markdown.cpython-310.pyc ADDED
Binary file (3.13 kB). View file
 
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_to_string.cpython-310.pyc ADDED
Binary file (36.5 kB). View file
 
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/__init__.py ADDED
File without changes
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (202 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_bar.cpython-310.pyc ADDED
Binary file (9.11 kB). View file
 
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_exceptions.cpython-310.pyc ADDED
Binary file (1.69 kB). View file
 
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_format.cpython-310.pyc ADDED
Binary file (18.6 kB). View file
 
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_html.cpython-310.pyc ADDED
Binary file (29.8 kB). View file
 
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_matplotlib.cpython-310.pyc ADDED
Binary file (9.07 kB). View file
 
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_non_unique.cpython-310.pyc ADDED
Binary file (4.15 kB). View file
 
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_style.cpython-310.pyc ADDED
Binary file (50.1 kB). View file
 
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_to_string.cpython-310.pyc ADDED
Binary file (2.14 kB). View file
 
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_tooltip.cpython-310.pyc ADDED
Binary file (2.68 kB). View file
 
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/test_bar.py ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ from pandas import (
7
+ NA,
8
+ DataFrame,
9
+ read_csv,
10
+ )
11
+
12
+ pytest.importorskip("jinja2")
13
+
14
+
15
+ def bar_grad(a=None, b=None, c=None, d=None):
16
+ """Used in multiple tests to simplify formatting of expected result"""
17
+ ret = [("width", "10em")]
18
+ if all(x is None for x in [a, b, c, d]):
19
+ return ret
20
+ return ret + [
21
+ (
22
+ "background",
23
+ f"linear-gradient(90deg,{','.join([x for x in [a, b, c, d] if x])})",
24
+ )
25
+ ]
26
+
27
+
28
+ def no_bar():
29
+ return bar_grad()
30
+
31
+
32
+ def bar_to(x, color="#d65f5f"):
33
+ return bar_grad(f" {color} {x:.1f}%", f" transparent {x:.1f}%")
34
+
35
+
36
+ def bar_from_to(x, y, color="#d65f5f"):
37
+ return bar_grad(
38
+ f" transparent {x:.1f}%",
39
+ f" {color} {x:.1f}%",
40
+ f" {color} {y:.1f}%",
41
+ f" transparent {y:.1f}%",
42
+ )
43
+
44
+
45
+ @pytest.fixture
46
+ def df_pos():
47
+ return DataFrame([[1], [2], [3]])
48
+
49
+
50
+ @pytest.fixture
51
+ def df_neg():
52
+ return DataFrame([[-1], [-2], [-3]])
53
+
54
+
55
+ @pytest.fixture
56
+ def df_mix():
57
+ return DataFrame([[-3], [1], [2]])
58
+
59
+
60
+ @pytest.mark.parametrize(
61
+ "align, exp",
62
+ [
63
+ ("left", [no_bar(), bar_to(50), bar_to(100)]),
64
+ ("right", [bar_to(100), bar_from_to(50, 100), no_bar()]),
65
+ ("mid", [bar_to(33.33), bar_to(66.66), bar_to(100)]),
66
+ ("zero", [bar_from_to(50, 66.7), bar_from_to(50, 83.3), bar_from_to(50, 100)]),
67
+ ("mean", [bar_to(50), no_bar(), bar_from_to(50, 100)]),
68
+ (2.0, [bar_to(50), no_bar(), bar_from_to(50, 100)]),
69
+ (np.median, [bar_to(50), no_bar(), bar_from_to(50, 100)]),
70
+ ],
71
+ )
72
+ def test_align_positive_cases(df_pos, align, exp):
73
+ # test different align cases for all positive values
74
+ result = df_pos.style.bar(align=align)._compute().ctx
75
+ expected = {(0, 0): exp[0], (1, 0): exp[1], (2, 0): exp[2]}
76
+ assert result == expected
77
+
78
+
79
+ @pytest.mark.parametrize(
80
+ "align, exp",
81
+ [
82
+ ("left", [bar_to(100), bar_to(50), no_bar()]),
83
+ ("right", [no_bar(), bar_from_to(50, 100), bar_to(100)]),
84
+ ("mid", [bar_from_to(66.66, 100), bar_from_to(33.33, 100), bar_to(100)]),
85
+ ("zero", [bar_from_to(33.33, 50), bar_from_to(16.66, 50), bar_to(50)]),
86
+ ("mean", [bar_from_to(50, 100), no_bar(), bar_to(50)]),
87
+ (-2.0, [bar_from_to(50, 100), no_bar(), bar_to(50)]),
88
+ (np.median, [bar_from_to(50, 100), no_bar(), bar_to(50)]),
89
+ ],
90
+ )
91
+ def test_align_negative_cases(df_neg, align, exp):
92
+ # test different align cases for all negative values
93
+ result = df_neg.style.bar(align=align)._compute().ctx
94
+ expected = {(0, 0): exp[0], (1, 0): exp[1], (2, 0): exp[2]}
95
+ assert result == expected
96
+
97
+
98
+ @pytest.mark.parametrize(
99
+ "align, exp",
100
+ [
101
+ ("left", [no_bar(), bar_to(80), bar_to(100)]),
102
+ ("right", [bar_to(100), bar_from_to(80, 100), no_bar()]),
103
+ ("mid", [bar_to(60), bar_from_to(60, 80), bar_from_to(60, 100)]),
104
+ ("zero", [bar_to(50), bar_from_to(50, 66.66), bar_from_to(50, 83.33)]),
105
+ ("mean", [bar_to(50), bar_from_to(50, 66.66), bar_from_to(50, 83.33)]),
106
+ (-0.0, [bar_to(50), bar_from_to(50, 66.66), bar_from_to(50, 83.33)]),
107
+ (np.nanmedian, [bar_to(50), no_bar(), bar_from_to(50, 62.5)]),
108
+ ],
109
+ )
110
+ @pytest.mark.parametrize("nans", [True, False])
111
+ def test_align_mixed_cases(df_mix, align, exp, nans):
112
+ # test different align cases for mixed positive and negative values
113
+ # also test no impact of NaNs and no_bar
114
+ expected = {(0, 0): exp[0], (1, 0): exp[1], (2, 0): exp[2]}
115
+ if nans:
116
+ df_mix.loc[3, :] = np.nan
117
+ expected.update({(3, 0): no_bar()})
118
+ result = df_mix.style.bar(align=align)._compute().ctx
119
+ assert result == expected
120
+
121
+
122
+ @pytest.mark.parametrize(
123
+ "align, exp",
124
+ [
125
+ (
126
+ "left",
127
+ {
128
+ "index": [[no_bar(), no_bar()], [bar_to(100), bar_to(100)]],
129
+ "columns": [[no_bar(), bar_to(100)], [no_bar(), bar_to(100)]],
130
+ "none": [[no_bar(), bar_to(33.33)], [bar_to(66.66), bar_to(100)]],
131
+ },
132
+ ),
133
+ (
134
+ "mid",
135
+ {
136
+ "index": [[bar_to(33.33), bar_to(50)], [bar_to(100), bar_to(100)]],
137
+ "columns": [[bar_to(50), bar_to(100)], [bar_to(75), bar_to(100)]],
138
+ "none": [[bar_to(25), bar_to(50)], [bar_to(75), bar_to(100)]],
139
+ },
140
+ ),
141
+ (
142
+ "zero",
143
+ {
144
+ "index": [
145
+ [bar_from_to(50, 66.66), bar_from_to(50, 75)],
146
+ [bar_from_to(50, 100), bar_from_to(50, 100)],
147
+ ],
148
+ "columns": [
149
+ [bar_from_to(50, 75), bar_from_to(50, 100)],
150
+ [bar_from_to(50, 87.5), bar_from_to(50, 100)],
151
+ ],
152
+ "none": [
153
+ [bar_from_to(50, 62.5), bar_from_to(50, 75)],
154
+ [bar_from_to(50, 87.5), bar_from_to(50, 100)],
155
+ ],
156
+ },
157
+ ),
158
+ (
159
+ 2,
160
+ {
161
+ "index": [
162
+ [bar_to(50), no_bar()],
163
+ [bar_from_to(50, 100), bar_from_to(50, 100)],
164
+ ],
165
+ "columns": [
166
+ [bar_to(50), no_bar()],
167
+ [bar_from_to(50, 75), bar_from_to(50, 100)],
168
+ ],
169
+ "none": [
170
+ [bar_from_to(25, 50), no_bar()],
171
+ [bar_from_to(50, 75), bar_from_to(50, 100)],
172
+ ],
173
+ },
174
+ ),
175
+ ],
176
+ )
177
+ @pytest.mark.parametrize("axis", ["index", "columns", "none"])
178
+ def test_align_axis(align, exp, axis):
179
+ # test all axis combinations with positive values and different aligns
180
+ data = DataFrame([[1, 2], [3, 4]])
181
+ result = (
182
+ data.style.bar(align=align, axis=None if axis == "none" else axis)
183
+ ._compute()
184
+ .ctx
185
+ )
186
+ expected = {
187
+ (0, 0): exp[axis][0][0],
188
+ (0, 1): exp[axis][0][1],
189
+ (1, 0): exp[axis][1][0],
190
+ (1, 1): exp[axis][1][1],
191
+ }
192
+ assert result == expected
193
+
194
+
195
+ @pytest.mark.parametrize(
196
+ "values, vmin, vmax",
197
+ [
198
+ ("positive", 1.5, 2.5),
199
+ ("negative", -2.5, -1.5),
200
+ ("mixed", -2.5, 1.5),
201
+ ],
202
+ )
203
+ @pytest.mark.parametrize("nullify", [None, "vmin", "vmax"]) # test min/max separately
204
+ @pytest.mark.parametrize("align", ["left", "right", "zero", "mid"])
205
+ def test_vmin_vmax_clipping(df_pos, df_neg, df_mix, values, vmin, vmax, nullify, align):
206
+ # test that clipping occurs if any vmin > data_values or vmax < data_values
207
+ if align == "mid": # mid acts as left or right in each case
208
+ if values == "positive":
209
+ align = "left"
210
+ elif values == "negative":
211
+ align = "right"
212
+ df = {"positive": df_pos, "negative": df_neg, "mixed": df_mix}[values]
213
+ vmin = None if nullify == "vmin" else vmin
214
+ vmax = None if nullify == "vmax" else vmax
215
+
216
+ clip_df = df.where(df <= (vmax if vmax else 999), other=vmax)
217
+ clip_df = clip_df.where(clip_df >= (vmin if vmin else -999), other=vmin)
218
+
219
+ result = (
220
+ df.style.bar(align=align, vmin=vmin, vmax=vmax, color=["red", "green"])
221
+ ._compute()
222
+ .ctx
223
+ )
224
+ expected = clip_df.style.bar(align=align, color=["red", "green"])._compute().ctx
225
+ assert result == expected
226
+
227
+
228
+ @pytest.mark.parametrize(
229
+ "values, vmin, vmax",
230
+ [
231
+ ("positive", 0.5, 4.5),
232
+ ("negative", -4.5, -0.5),
233
+ ("mixed", -4.5, 4.5),
234
+ ],
235
+ )
236
+ @pytest.mark.parametrize("nullify", [None, "vmin", "vmax"]) # test min/max separately
237
+ @pytest.mark.parametrize("align", ["left", "right", "zero", "mid"])
238
+ def test_vmin_vmax_widening(df_pos, df_neg, df_mix, values, vmin, vmax, nullify, align):
239
+ # test that widening occurs if any vmax > data_values or vmin < data_values
240
+ if align == "mid": # mid acts as left or right in each case
241
+ if values == "positive":
242
+ align = "left"
243
+ elif values == "negative":
244
+ align = "right"
245
+ df = {"positive": df_pos, "negative": df_neg, "mixed": df_mix}[values]
246
+ vmin = None if nullify == "vmin" else vmin
247
+ vmax = None if nullify == "vmax" else vmax
248
+
249
+ expand_df = df.copy()
250
+ expand_df.loc[3, :], expand_df.loc[4, :] = vmin, vmax
251
+
252
+ result = (
253
+ df.style.bar(align=align, vmin=vmin, vmax=vmax, color=["red", "green"])
254
+ ._compute()
255
+ .ctx
256
+ )
257
+ expected = expand_df.style.bar(align=align, color=["red", "green"])._compute().ctx
258
+ assert result.items() <= expected.items()
259
+
260
+
261
+ def test_numerics():
262
+ # test data is pre-selected for numeric values
263
+ data = DataFrame([[1, "a"], [2, "b"]])
264
+ result = data.style.bar()._compute().ctx
265
+ assert (0, 1) not in result
266
+ assert (1, 1) not in result
267
+
268
+
269
+ @pytest.mark.parametrize(
270
+ "align, exp",
271
+ [
272
+ ("left", [no_bar(), bar_to(100, "green")]),
273
+ ("right", [bar_to(100, "red"), no_bar()]),
274
+ ("mid", [bar_to(25, "red"), bar_from_to(25, 100, "green")]),
275
+ ("zero", [bar_from_to(33.33, 50, "red"), bar_from_to(50, 100, "green")]),
276
+ ],
277
+ )
278
+ def test_colors_mixed(align, exp):
279
+ data = DataFrame([[-1], [3]])
280
+ result = data.style.bar(align=align, color=["red", "green"])._compute().ctx
281
+ assert result == {(0, 0): exp[0], (1, 0): exp[1]}
282
+
283
+
284
+ def test_bar_align_height():
285
+ # test when keyword height is used 'no-repeat center' and 'background-size' present
286
+ data = DataFrame([[1], [2]])
287
+ result = data.style.bar(align="left", height=50)._compute().ctx
288
+ bg_s = "linear-gradient(90deg, #d65f5f 100.0%, transparent 100.0%) no-repeat center"
289
+ expected = {
290
+ (0, 0): [("width", "10em")],
291
+ (1, 0): [
292
+ ("width", "10em"),
293
+ ("background", bg_s),
294
+ ("background-size", "100% 50.0%"),
295
+ ],
296
+ }
297
+ assert result == expected
298
+
299
+
300
+ def test_bar_value_error_raises():
301
+ df = DataFrame({"A": [-100, -60, -30, -20]})
302
+
303
+ msg = "`align` should be in {'left', 'right', 'mid', 'mean', 'zero'} or"
304
+ with pytest.raises(ValueError, match=msg):
305
+ df.style.bar(align="poorly", color=["#d65f5f", "#5fba7d"]).to_html()
306
+
307
+ msg = r"`width` must be a value in \[0, 100\]"
308
+ with pytest.raises(ValueError, match=msg):
309
+ df.style.bar(width=200).to_html()
310
+
311
+ msg = r"`height` must be a value in \[0, 100\]"
312
+ with pytest.raises(ValueError, match=msg):
313
+ df.style.bar(height=200).to_html()
314
+
315
+
316
+ def test_bar_color_and_cmap_error_raises():
317
+ df = DataFrame({"A": [1, 2, 3, 4]})
318
+ msg = "`color` and `cmap` cannot both be given"
319
+ # Test that providing both color and cmap raises a ValueError
320
+ with pytest.raises(ValueError, match=msg):
321
+ df.style.bar(color="#d65f5f", cmap="viridis").to_html()
322
+
323
+
324
+ def test_bar_invalid_color_type_error_raises():
325
+ df = DataFrame({"A": [1, 2, 3, 4]})
326
+ msg = (
327
+ r"`color` must be string or list or tuple of 2 strings,"
328
+ r"\(eg: color=\['#d65f5f', '#5fba7d'\]\)"
329
+ )
330
+ # Test that providing an invalid color type raises a ValueError
331
+ with pytest.raises(ValueError, match=msg):
332
+ df.style.bar(color=123).to_html()
333
+
334
+ # Test that providing a color list with more than two elements raises a ValueError
335
+ with pytest.raises(ValueError, match=msg):
336
+ df.style.bar(color=["#d65f5f", "#5fba7d", "#abcdef"]).to_html()
337
+
338
+
339
+ def test_styler_bar_with_NA_values():
340
+ df1 = DataFrame({"A": [1, 2, NA, 4]})
341
+ df2 = DataFrame([[NA, NA], [NA, NA]])
342
+ expected_substring = "style type="
343
+ html_output1 = df1.style.bar(subset="A").to_html()
344
+ html_output2 = df2.style.bar(align="left", axis=None).to_html()
345
+ assert expected_substring in html_output1
346
+ assert expected_substring in html_output2
347
+
348
+
349
+ def test_style_bar_with_pyarrow_NA_values():
350
+ data = """name,age,test1,test2,teacher
351
+ Adam,15,95.0,80,Ashby
352
+ Bob,16,81.0,82,Ashby
353
+ Dave,16,89.0,84,Jones
354
+ Fred,15,,88,Jones"""
355
+ df = read_csv(io.StringIO(data), dtype_backend="pyarrow")
356
+ expected_substring = "style type="
357
+ html_output = df.style.bar(subset="test1").to_html()
358
+ assert expected_substring in html_output
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/test_exceptions.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ jinja2 = pytest.importorskip("jinja2")
4
+
5
+ from pandas import (
6
+ DataFrame,
7
+ MultiIndex,
8
+ )
9
+
10
+ from pandas.io.formats.style import Styler
11
+
12
+
13
+ @pytest.fixture
14
+ def df():
15
+ return DataFrame(
16
+ data=[[0, -0.609], [1, -1.228]],
17
+ columns=["A", "B"],
18
+ index=["x", "y"],
19
+ )
20
+
21
+
22
+ @pytest.fixture
23
+ def styler(df):
24
+ return Styler(df, uuid_len=0)
25
+
26
+
27
+ def test_concat_bad_columns(styler):
28
+ msg = "`other.data` must have same columns as `Styler.data"
29
+ with pytest.raises(ValueError, match=msg):
30
+ styler.concat(DataFrame([[1, 2]]).style)
31
+
32
+
33
+ def test_concat_bad_type(styler):
34
+ msg = "`other` must be of type `Styler`"
35
+ with pytest.raises(TypeError, match=msg):
36
+ styler.concat(DataFrame([[1, 2]]))
37
+
38
+
39
+ def test_concat_bad_index_levels(styler, df):
40
+ df = df.copy()
41
+ df.index = MultiIndex.from_tuples([(0, 0), (1, 1)])
42
+ msg = "number of index levels must be same in `other`"
43
+ with pytest.raises(ValueError, match=msg):
44
+ styler.concat(df.style)
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/test_format.py ADDED
@@ -0,0 +1,562 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas import (
5
+ NA,
6
+ DataFrame,
7
+ IndexSlice,
8
+ MultiIndex,
9
+ NaT,
10
+ Timestamp,
11
+ option_context,
12
+ )
13
+
14
+ pytest.importorskip("jinja2")
15
+ from pandas.io.formats.style import Styler
16
+ from pandas.io.formats.style_render import _str_escape
17
+
18
+
19
+ @pytest.fixture
20
+ def df():
21
+ return DataFrame(
22
+ data=[[0, -0.609], [1, -1.228]],
23
+ columns=["A", "B"],
24
+ index=["x", "y"],
25
+ )
26
+
27
+
28
+ @pytest.fixture
29
+ def styler(df):
30
+ return Styler(df, uuid_len=0)
31
+
32
+
33
+ @pytest.fixture
34
+ def df_multi():
35
+ return DataFrame(
36
+ data=np.arange(16).reshape(4, 4),
37
+ columns=MultiIndex.from_product([["A", "B"], ["a", "b"]]),
38
+ index=MultiIndex.from_product([["X", "Y"], ["x", "y"]]),
39
+ )
40
+
41
+
42
+ @pytest.fixture
43
+ def styler_multi(df_multi):
44
+ return Styler(df_multi, uuid_len=0)
45
+
46
+
47
+ def test_display_format(styler):
48
+ ctx = styler.format("{:0.1f}")._translate(True, True)
49
+ assert all(["display_value" in c for c in row] for row in ctx["body"])
50
+ assert all([len(c["display_value"]) <= 3 for c in row[1:]] for row in ctx["body"])
51
+ assert len(ctx["body"][0][1]["display_value"].lstrip("-")) <= 3
52
+
53
+
54
+ @pytest.mark.parametrize("index", [True, False])
55
+ @pytest.mark.parametrize("columns", [True, False])
56
+ def test_display_format_index(styler, index, columns):
57
+ exp_index = ["x", "y"]
58
+ if index:
59
+ styler.format_index(lambda v: v.upper(), axis=0) # test callable
60
+ exp_index = ["X", "Y"]
61
+
62
+ exp_columns = ["A", "B"]
63
+ if columns:
64
+ styler.format_index("*{}*", axis=1) # test string
65
+ exp_columns = ["*A*", "*B*"]
66
+
67
+ ctx = styler._translate(True, True)
68
+
69
+ for r, row in enumerate(ctx["body"]):
70
+ assert row[0]["display_value"] == exp_index[r]
71
+
72
+ for c, col in enumerate(ctx["head"][1:]):
73
+ assert col["display_value"] == exp_columns[c]
74
+
75
+
76
+ def test_format_dict(styler):
77
+ ctx = styler.format({"A": "{:0.1f}", "B": "{0:.2%}"})._translate(True, True)
78
+ assert ctx["body"][0][1]["display_value"] == "0.0"
79
+ assert ctx["body"][0][2]["display_value"] == "-60.90%"
80
+
81
+
82
+ def test_format_index_dict(styler):
83
+ ctx = styler.format_index({0: lambda v: v.upper()})._translate(True, True)
84
+ for i, val in enumerate(["X", "Y"]):
85
+ assert ctx["body"][i][0]["display_value"] == val
86
+
87
+
88
+ def test_format_string(styler):
89
+ ctx = styler.format("{:.2f}")._translate(True, True)
90
+ assert ctx["body"][0][1]["display_value"] == "0.00"
91
+ assert ctx["body"][0][2]["display_value"] == "-0.61"
92
+ assert ctx["body"][1][1]["display_value"] == "1.00"
93
+ assert ctx["body"][1][2]["display_value"] == "-1.23"
94
+
95
+
96
+ def test_format_callable(styler):
97
+ ctx = styler.format(lambda v: "neg" if v < 0 else "pos")._translate(True, True)
98
+ assert ctx["body"][0][1]["display_value"] == "pos"
99
+ assert ctx["body"][0][2]["display_value"] == "neg"
100
+ assert ctx["body"][1][1]["display_value"] == "pos"
101
+ assert ctx["body"][1][2]["display_value"] == "neg"
102
+
103
+
104
+ def test_format_with_na_rep():
105
+ # GH 21527 28358
106
+ df = DataFrame([[None, None], [1.1, 1.2]], columns=["A", "B"])
107
+
108
+ ctx = df.style.format(None, na_rep="-")._translate(True, True)
109
+ assert ctx["body"][0][1]["display_value"] == "-"
110
+ assert ctx["body"][0][2]["display_value"] == "-"
111
+
112
+ ctx = df.style.format("{:.2%}", na_rep="-")._translate(True, True)
113
+ assert ctx["body"][0][1]["display_value"] == "-"
114
+ assert ctx["body"][0][2]["display_value"] == "-"
115
+ assert ctx["body"][1][1]["display_value"] == "110.00%"
116
+ assert ctx["body"][1][2]["display_value"] == "120.00%"
117
+
118
+ ctx = df.style.format("{:.2%}", na_rep="-", subset=["B"])._translate(True, True)
119
+ assert ctx["body"][0][2]["display_value"] == "-"
120
+ assert ctx["body"][1][2]["display_value"] == "120.00%"
121
+
122
+
123
+ def test_format_index_with_na_rep():
124
+ df = DataFrame([[1, 2, 3, 4, 5]], columns=["A", None, np.nan, NaT, NA])
125
+ ctx = df.style.format_index(None, na_rep="--", axis=1)._translate(True, True)
126
+ assert ctx["head"][0][1]["display_value"] == "A"
127
+ for i in [2, 3, 4, 5]:
128
+ assert ctx["head"][0][i]["display_value"] == "--"
129
+
130
+
131
+ def test_format_non_numeric_na():
132
+ # GH 21527 28358
133
+ df = DataFrame(
134
+ {
135
+ "object": [None, np.nan, "foo"],
136
+ "datetime": [None, NaT, Timestamp("20120101")],
137
+ }
138
+ )
139
+ ctx = df.style.format(None, na_rep="-")._translate(True, True)
140
+ assert ctx["body"][0][1]["display_value"] == "-"
141
+ assert ctx["body"][0][2]["display_value"] == "-"
142
+ assert ctx["body"][1][1]["display_value"] == "-"
143
+ assert ctx["body"][1][2]["display_value"] == "-"
144
+
145
+
146
+ @pytest.mark.parametrize(
147
+ "func, attr, kwargs",
148
+ [
149
+ ("format", "_display_funcs", {}),
150
+ ("format_index", "_display_funcs_index", {"axis": 0}),
151
+ ("format_index", "_display_funcs_columns", {"axis": 1}),
152
+ ],
153
+ )
154
+ def test_format_clear(styler, func, attr, kwargs):
155
+ assert (0, 0) not in getattr(styler, attr) # using default
156
+ getattr(styler, func)("{:.2f}", **kwargs)
157
+ assert (0, 0) in getattr(styler, attr) # formatter is specified
158
+ getattr(styler, func)(**kwargs)
159
+ assert (0, 0) not in getattr(styler, attr) # formatter cleared to default
160
+
161
+
162
+ @pytest.mark.parametrize(
163
+ "escape, exp",
164
+ [
165
+ ("html", "&lt;&gt;&amp;&#34;%$#_{}~^\\~ ^ \\ "),
166
+ (
167
+ "latex",
168
+ '<>\\&"\\%\\$\\#\\_\\{\\}\\textasciitilde \\textasciicircum '
169
+ "\\textbackslash \\textasciitilde \\space \\textasciicircum \\space "
170
+ "\\textbackslash \\space ",
171
+ ),
172
+ ],
173
+ )
174
+ def test_format_escape_html(escape, exp):
175
+ chars = '<>&"%$#_{}~^\\~ ^ \\ '
176
+ df = DataFrame([[chars]])
177
+
178
+ s = Styler(df, uuid_len=0).format("&{0}&", escape=None)
179
+ expected = f'<td id="T__row0_col0" class="data row0 col0" >&{chars}&</td>'
180
+ assert expected in s.to_html()
181
+
182
+ # only the value should be escaped before passing to the formatter
183
+ s = Styler(df, uuid_len=0).format("&{0}&", escape=escape)
184
+ expected = f'<td id="T__row0_col0" class="data row0 col0" >&{exp}&</td>'
185
+ assert expected in s.to_html()
186
+
187
+ # also test format_index()
188
+ styler = Styler(DataFrame(columns=[chars]), uuid_len=0)
189
+ styler.format_index("&{0}&", escape=None, axis=1)
190
+ assert styler._translate(True, True)["head"][0][1]["display_value"] == f"&{chars}&"
191
+ styler.format_index("&{0}&", escape=escape, axis=1)
192
+ assert styler._translate(True, True)["head"][0][1]["display_value"] == f"&{exp}&"
193
+
194
+
195
+ @pytest.mark.parametrize(
196
+ "chars, expected",
197
+ [
198
+ (
199
+ r"$ \$&%#_{}~^\ $ &%#_{}~^\ $",
200
+ "".join(
201
+ [
202
+ r"$ \$&%#_{}~^\ $ ",
203
+ r"\&\%\#\_\{\}\textasciitilde \textasciicircum ",
204
+ r"\textbackslash \space \$",
205
+ ]
206
+ ),
207
+ ),
208
+ (
209
+ r"\( &%#_{}~^\ \) &%#_{}~^\ \(",
210
+ "".join(
211
+ [
212
+ r"\( &%#_{}~^\ \) ",
213
+ r"\&\%\#\_\{\}\textasciitilde \textasciicircum ",
214
+ r"\textbackslash \space \textbackslash (",
215
+ ]
216
+ ),
217
+ ),
218
+ (
219
+ r"$\&%#_{}^\$",
220
+ r"\$\textbackslash \&\%\#\_\{\}\textasciicircum \textbackslash \$",
221
+ ),
222
+ (
223
+ r"$ \frac{1}{2} $ \( \frac{1}{2} \)",
224
+ "".join(
225
+ [
226
+ r"$ \frac{1}{2} $",
227
+ r" \textbackslash ( \textbackslash frac\{1\}\{2\} \textbackslash )",
228
+ ]
229
+ ),
230
+ ),
231
+ ],
232
+ )
233
+ def test_format_escape_latex_math(chars, expected):
234
+ # GH 51903
235
+ # latex-math escape works for each DataFrame cell separately. If we have
236
+ # a combination of dollar signs and brackets, the dollar sign would apply.
237
+ df = DataFrame([[chars]])
238
+ s = df.style.format("{0}", escape="latex-math")
239
+ assert s._translate(True, True)["body"][0][1]["display_value"] == expected
240
+
241
+
242
+ def test_format_escape_na_rep():
243
+ # tests the na_rep is not escaped
244
+ df = DataFrame([['<>&"', None]])
245
+ s = Styler(df, uuid_len=0).format("X&{0}>X", escape="html", na_rep="&")
246
+ ex = '<td id="T__row0_col0" class="data row0 col0" >X&&lt;&gt;&amp;&#34;>X</td>'
247
+ expected2 = '<td id="T__row0_col1" class="data row0 col1" >&</td>'
248
+ assert ex in s.to_html()
249
+ assert expected2 in s.to_html()
250
+
251
+ # also test for format_index()
252
+ df = DataFrame(columns=['<>&"', None])
253
+ styler = Styler(df, uuid_len=0)
254
+ styler.format_index("X&{0}>X", escape="html", na_rep="&", axis=1)
255
+ ctx = styler._translate(True, True)
256
+ assert ctx["head"][0][1]["display_value"] == "X&&lt;&gt;&amp;&#34;>X"
257
+ assert ctx["head"][0][2]["display_value"] == "&"
258
+
259
+
260
+ def test_format_escape_floats(styler):
261
+ # test given formatter for number format is not impacted by escape
262
+ s = styler.format("{:.1f}", escape="html")
263
+ for expected in [">0.0<", ">1.0<", ">-1.2<", ">-0.6<"]:
264
+ assert expected in s.to_html()
265
+ # tests precision of floats is not impacted by escape
266
+ s = styler.format(precision=1, escape="html")
267
+ for expected in [">0<", ">1<", ">-1.2<", ">-0.6<"]:
268
+ assert expected in s.to_html()
269
+
270
+
271
+ @pytest.mark.parametrize("formatter", [5, True, [2.0]])
272
+ @pytest.mark.parametrize("func", ["format", "format_index"])
273
+ def test_format_raises(styler, formatter, func):
274
+ with pytest.raises(TypeError, match="expected str or callable"):
275
+ getattr(styler, func)(formatter)
276
+
277
+
278
+ @pytest.mark.parametrize(
279
+ "precision, expected",
280
+ [
281
+ (1, ["1.0", "2.0", "3.2", "4.6"]),
282
+ (2, ["1.00", "2.01", "3.21", "4.57"]),
283
+ (3, ["1.000", "2.009", "3.212", "4.566"]),
284
+ ],
285
+ )
286
+ def test_format_with_precision(precision, expected):
287
+ # Issue #13257
288
+ df = DataFrame([[1.0, 2.0090, 3.2121, 4.566]], columns=[1.0, 2.0090, 3.2121, 4.566])
289
+ styler = Styler(df)
290
+ styler.format(precision=precision)
291
+ styler.format_index(precision=precision, axis=1)
292
+
293
+ ctx = styler._translate(True, True)
294
+ for col, exp in enumerate(expected):
295
+ assert ctx["body"][0][col + 1]["display_value"] == exp # format test
296
+ assert ctx["head"][0][col + 1]["display_value"] == exp # format_index test
297
+
298
+
299
+ @pytest.mark.parametrize("axis", [0, 1])
300
+ @pytest.mark.parametrize(
301
+ "level, expected",
302
+ [
303
+ (0, ["X", "X", "_", "_"]), # level int
304
+ ("zero", ["X", "X", "_", "_"]), # level name
305
+ (1, ["_", "_", "X", "X"]), # other level int
306
+ ("one", ["_", "_", "X", "X"]), # other level name
307
+ ([0, 1], ["X", "X", "X", "X"]), # both levels
308
+ ([0, "zero"], ["X", "X", "_", "_"]), # level int and name simultaneous
309
+ ([0, "one"], ["X", "X", "X", "X"]), # both levels as int and name
310
+ (["one", "zero"], ["X", "X", "X", "X"]), # both level names, reversed
311
+ ],
312
+ )
313
+ def test_format_index_level(axis, level, expected):
314
+ midx = MultiIndex.from_arrays([["_", "_"], ["_", "_"]], names=["zero", "one"])
315
+ df = DataFrame([[1, 2], [3, 4]])
316
+ if axis == 0:
317
+ df.index = midx
318
+ else:
319
+ df.columns = midx
320
+
321
+ styler = df.style.format_index(lambda v: "X", level=level, axis=axis)
322
+ ctx = styler._translate(True, True)
323
+
324
+ if axis == 0: # compare index
325
+ result = [ctx["body"][s][0]["display_value"] for s in range(2)]
326
+ result += [ctx["body"][s][1]["display_value"] for s in range(2)]
327
+ else: # compare columns
328
+ result = [ctx["head"][0][s + 1]["display_value"] for s in range(2)]
329
+ result += [ctx["head"][1][s + 1]["display_value"] for s in range(2)]
330
+
331
+ assert expected == result
332
+
333
+
334
+ def test_format_subset():
335
+ df = DataFrame([[0.1234, 0.1234], [1.1234, 1.1234]], columns=["a", "b"])
336
+ ctx = df.style.format(
337
+ {"a": "{:0.1f}", "b": "{0:.2%}"}, subset=IndexSlice[0, :]
338
+ )._translate(True, True)
339
+ expected = "0.1"
340
+ raw_11 = "1.123400"
341
+ assert ctx["body"][0][1]["display_value"] == expected
342
+ assert ctx["body"][1][1]["display_value"] == raw_11
343
+ assert ctx["body"][0][2]["display_value"] == "12.34%"
344
+
345
+ ctx = df.style.format("{:0.1f}", subset=IndexSlice[0, :])._translate(True, True)
346
+ assert ctx["body"][0][1]["display_value"] == expected
347
+ assert ctx["body"][1][1]["display_value"] == raw_11
348
+
349
+ ctx = df.style.format("{:0.1f}", subset=IndexSlice["a"])._translate(True, True)
350
+ assert ctx["body"][0][1]["display_value"] == expected
351
+ assert ctx["body"][0][2]["display_value"] == "0.123400"
352
+
353
+ ctx = df.style.format("{:0.1f}", subset=IndexSlice[0, "a"])._translate(True, True)
354
+ assert ctx["body"][0][1]["display_value"] == expected
355
+ assert ctx["body"][1][1]["display_value"] == raw_11
356
+
357
+ ctx = df.style.format("{:0.1f}", subset=IndexSlice[[0, 1], ["a"]])._translate(
358
+ True, True
359
+ )
360
+ assert ctx["body"][0][1]["display_value"] == expected
361
+ assert ctx["body"][1][1]["display_value"] == "1.1"
362
+ assert ctx["body"][0][2]["display_value"] == "0.123400"
363
+ assert ctx["body"][1][2]["display_value"] == raw_11
364
+
365
+
366
+ @pytest.mark.parametrize("formatter", [None, "{:,.1f}"])
367
+ @pytest.mark.parametrize("decimal", [".", "*"])
368
+ @pytest.mark.parametrize("precision", [None, 2])
369
+ @pytest.mark.parametrize("func, col", [("format", 1), ("format_index", 0)])
370
+ def test_format_thousands(formatter, decimal, precision, func, col):
371
+ styler = DataFrame([[1000000.123456789]], index=[1000000.123456789]).style
372
+ result = getattr(styler, func)( # testing float
373
+ thousands="_", formatter=formatter, decimal=decimal, precision=precision
374
+ )._translate(True, True)
375
+ assert "1_000_000" in result["body"][0][col]["display_value"]
376
+
377
+ styler = DataFrame([[1000000]], index=[1000000]).style
378
+ result = getattr(styler, func)( # testing int
379
+ thousands="_", formatter=formatter, decimal=decimal, precision=precision
380
+ )._translate(True, True)
381
+ assert "1_000_000" in result["body"][0][col]["display_value"]
382
+
383
+ styler = DataFrame([[1 + 1000000.123456789j]], index=[1 + 1000000.123456789j]).style
384
+ result = getattr(styler, func)( # testing complex
385
+ thousands="_", formatter=formatter, decimal=decimal, precision=precision
386
+ )._translate(True, True)
387
+ assert "1_000_000" in result["body"][0][col]["display_value"]
388
+
389
+
390
+ @pytest.mark.parametrize("formatter", [None, "{:,.4f}"])
391
+ @pytest.mark.parametrize("thousands", [None, ",", "*"])
392
+ @pytest.mark.parametrize("precision", [None, 4])
393
+ @pytest.mark.parametrize("func, col", [("format", 1), ("format_index", 0)])
394
+ def test_format_decimal(formatter, thousands, precision, func, col):
395
+ styler = DataFrame([[1000000.123456789]], index=[1000000.123456789]).style
396
+ result = getattr(styler, func)( # testing float
397
+ decimal="_", formatter=formatter, thousands=thousands, precision=precision
398
+ )._translate(True, True)
399
+ assert "000_123" in result["body"][0][col]["display_value"]
400
+
401
+ styler = DataFrame([[1 + 1000000.123456789j]], index=[1 + 1000000.123456789j]).style
402
+ result = getattr(styler, func)( # testing complex
403
+ decimal="_", formatter=formatter, thousands=thousands, precision=precision
404
+ )._translate(True, True)
405
+ assert "000_123" in result["body"][0][col]["display_value"]
406
+
407
+
408
+ def test_str_escape_error():
409
+ msg = "`escape` only permitted in {'html', 'latex', 'latex-math'}, got "
410
+ with pytest.raises(ValueError, match=msg):
411
+ _str_escape("text", "bad_escape")
412
+
413
+ with pytest.raises(ValueError, match=msg):
414
+ _str_escape("text", [])
415
+
416
+ _str_escape(2.00, "bad_escape") # OK since dtype is float
417
+
418
+
419
+ def test_long_int_formatting():
420
+ df = DataFrame(data=[[1234567890123456789]], columns=["test"])
421
+ styler = df.style
422
+ ctx = styler._translate(True, True)
423
+ assert ctx["body"][0][1]["display_value"] == "1234567890123456789"
424
+
425
+ styler = df.style.format(thousands="_")
426
+ ctx = styler._translate(True, True)
427
+ assert ctx["body"][0][1]["display_value"] == "1_234_567_890_123_456_789"
428
+
429
+
430
+ def test_format_options():
431
+ df = DataFrame({"int": [2000, 1], "float": [1.009, None], "str": ["&<", "&~"]})
432
+ ctx = df.style._translate(True, True)
433
+
434
+ # test option: na_rep
435
+ assert ctx["body"][1][2]["display_value"] == "nan"
436
+ with option_context("styler.format.na_rep", "MISSING"):
437
+ ctx_with_op = df.style._translate(True, True)
438
+ assert ctx_with_op["body"][1][2]["display_value"] == "MISSING"
439
+
440
+ # test option: decimal and precision
441
+ assert ctx["body"][0][2]["display_value"] == "1.009000"
442
+ with option_context("styler.format.decimal", "_"):
443
+ ctx_with_op = df.style._translate(True, True)
444
+ assert ctx_with_op["body"][0][2]["display_value"] == "1_009000"
445
+ with option_context("styler.format.precision", 2):
446
+ ctx_with_op = df.style._translate(True, True)
447
+ assert ctx_with_op["body"][0][2]["display_value"] == "1.01"
448
+
449
+ # test option: thousands
450
+ assert ctx["body"][0][1]["display_value"] == "2000"
451
+ with option_context("styler.format.thousands", "_"):
452
+ ctx_with_op = df.style._translate(True, True)
453
+ assert ctx_with_op["body"][0][1]["display_value"] == "2_000"
454
+
455
+ # test option: escape
456
+ assert ctx["body"][0][3]["display_value"] == "&<"
457
+ assert ctx["body"][1][3]["display_value"] == "&~"
458
+ with option_context("styler.format.escape", "html"):
459
+ ctx_with_op = df.style._translate(True, True)
460
+ assert ctx_with_op["body"][0][3]["display_value"] == "&amp;&lt;"
461
+ with option_context("styler.format.escape", "latex"):
462
+ ctx_with_op = df.style._translate(True, True)
463
+ assert ctx_with_op["body"][1][3]["display_value"] == "\\&\\textasciitilde "
464
+ with option_context("styler.format.escape", "latex-math"):
465
+ ctx_with_op = df.style._translate(True, True)
466
+ assert ctx_with_op["body"][1][3]["display_value"] == "\\&\\textasciitilde "
467
+
468
+ # test option: formatter
469
+ with option_context("styler.format.formatter", {"int": "{:,.2f}"}):
470
+ ctx_with_op = df.style._translate(True, True)
471
+ assert ctx_with_op["body"][0][1]["display_value"] == "2,000.00"
472
+
473
+
474
+ def test_precision_zero(df):
475
+ styler = Styler(df, precision=0)
476
+ ctx = styler._translate(True, True)
477
+ assert ctx["body"][0][2]["display_value"] == "-1"
478
+ assert ctx["body"][1][2]["display_value"] == "-1"
479
+
480
+
481
+ @pytest.mark.parametrize(
482
+ "formatter, exp",
483
+ [
484
+ (lambda x: f"{x:.3f}", "9.000"),
485
+ ("{:.2f}", "9.00"),
486
+ ({0: "{:.1f}"}, "9.0"),
487
+ (None, "9"),
488
+ ],
489
+ )
490
+ def test_formatter_options_validator(formatter, exp):
491
+ df = DataFrame([[9]])
492
+ with option_context("styler.format.formatter", formatter):
493
+ assert f" {exp} " in df.style.to_latex()
494
+
495
+
496
+ def test_formatter_options_raises():
497
+ msg = "Value must be an instance of"
498
+ with pytest.raises(ValueError, match=msg):
499
+ with option_context("styler.format.formatter", ["bad", "type"]):
500
+ DataFrame().style.to_latex()
501
+
502
+
503
+ def test_1level_multiindex():
504
+ # GH 43383
505
+ midx = MultiIndex.from_product([[1, 2]], names=[""])
506
+ df = DataFrame(-1, index=midx, columns=[0, 1])
507
+ ctx = df.style._translate(True, True)
508
+ assert ctx["body"][0][0]["display_value"] == "1"
509
+ assert ctx["body"][0][0]["is_visible"] is True
510
+ assert ctx["body"][1][0]["display_value"] == "2"
511
+ assert ctx["body"][1][0]["is_visible"] is True
512
+
513
+
514
+ def test_boolean_format():
515
+ # gh 46384: booleans do not collapse to integer representation on display
516
+ df = DataFrame([[True, False]])
517
+ ctx = df.style._translate(True, True)
518
+ assert ctx["body"][0][1]["display_value"] is True
519
+ assert ctx["body"][0][2]["display_value"] is False
520
+
521
+
522
+ @pytest.mark.parametrize(
523
+ "hide, labels",
524
+ [
525
+ (False, [1, 2]),
526
+ (True, [1, 2, 3, 4]),
527
+ ],
528
+ )
529
+ def test_relabel_raise_length(styler_multi, hide, labels):
530
+ if hide:
531
+ styler_multi.hide(axis=0, subset=[("X", "x"), ("Y", "y")])
532
+ with pytest.raises(ValueError, match="``labels`` must be of length equal"):
533
+ styler_multi.relabel_index(labels=labels)
534
+
535
+
536
+ def test_relabel_index(styler_multi):
537
+ labels = [(1, 2), (3, 4)]
538
+ styler_multi.hide(axis=0, subset=[("X", "x"), ("Y", "y")])
539
+ styler_multi.relabel_index(labels=labels)
540
+ ctx = styler_multi._translate(True, True)
541
+ assert {"value": "X", "display_value": 1}.items() <= ctx["body"][0][0].items()
542
+ assert {"value": "y", "display_value": 2}.items() <= ctx["body"][0][1].items()
543
+ assert {"value": "Y", "display_value": 3}.items() <= ctx["body"][1][0].items()
544
+ assert {"value": "x", "display_value": 4}.items() <= ctx["body"][1][1].items()
545
+
546
+
547
+ def test_relabel_columns(styler_multi):
548
+ labels = [(1, 2), (3, 4)]
549
+ styler_multi.hide(axis=1, subset=[("A", "a"), ("B", "b")])
550
+ styler_multi.relabel_index(axis=1, labels=labels)
551
+ ctx = styler_multi._translate(True, True)
552
+ assert {"value": "A", "display_value": 1}.items() <= ctx["head"][0][3].items()
553
+ assert {"value": "B", "display_value": 3}.items() <= ctx["head"][0][4].items()
554
+ assert {"value": "b", "display_value": 2}.items() <= ctx["head"][1][3].items()
555
+ assert {"value": "a", "display_value": 4}.items() <= ctx["head"][1][4].items()
556
+
557
+
558
+ def test_relabel_roundtrip(styler):
559
+ styler.relabel_index(["{}", "{}"])
560
+ ctx = styler._translate(True, True)
561
+ assert {"value": "x", "display_value": "x"}.items() <= ctx["body"][0][0].items()
562
+ assert {"value": "y", "display_value": "y"}.items() <= ctx["body"][1][0].items()
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/test_highlight.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas import (
5
+ NA,
6
+ DataFrame,
7
+ IndexSlice,
8
+ )
9
+
10
+ pytest.importorskip("jinja2")
11
+
12
+ from pandas.io.formats.style import Styler
13
+
14
+
15
+ @pytest.fixture(params=[(None, "float64"), (NA, "Int64")])
16
+ def df(request):
17
+ # GH 45804
18
+ return DataFrame(
19
+ {"A": [0, np.nan, 10], "B": [1, request.param[0], 2]}, dtype=request.param[1]
20
+ )
21
+
22
+
23
+ @pytest.fixture
24
+ def styler(df):
25
+ return Styler(df, uuid_len=0)
26
+
27
+
28
+ def test_highlight_null(styler):
29
+ result = styler.highlight_null()._compute().ctx
30
+ expected = {
31
+ (1, 0): [("background-color", "red")],
32
+ (1, 1): [("background-color", "red")],
33
+ }
34
+ assert result == expected
35
+
36
+
37
+ def test_highlight_null_subset(styler):
38
+ # GH 31345
39
+ result = (
40
+ styler.highlight_null(color="red", subset=["A"])
41
+ .highlight_null(color="green", subset=["B"])
42
+ ._compute()
43
+ .ctx
44
+ )
45
+ expected = {
46
+ (1, 0): [("background-color", "red")],
47
+ (1, 1): [("background-color", "green")],
48
+ }
49
+ assert result == expected
50
+
51
+
52
+ @pytest.mark.parametrize("f", ["highlight_min", "highlight_max"])
53
+ def test_highlight_minmax_basic(df, f):
54
+ expected = {
55
+ (0, 1): [("background-color", "red")],
56
+ # ignores NaN row,
57
+ (2, 0): [("background-color", "red")],
58
+ }
59
+ if f == "highlight_min":
60
+ df = -df
61
+ result = getattr(df.style, f)(axis=1, color="red")._compute().ctx
62
+ assert result == expected
63
+
64
+
65
+ @pytest.mark.parametrize("f", ["highlight_min", "highlight_max"])
66
+ @pytest.mark.parametrize(
67
+ "kwargs",
68
+ [
69
+ {"axis": None, "color": "red"}, # test axis
70
+ {"axis": 0, "subset": ["A"], "color": "red"}, # test subset and ignores NaN
71
+ {"axis": None, "props": "background-color: red"}, # test props
72
+ ],
73
+ )
74
+ def test_highlight_minmax_ext(df, f, kwargs):
75
+ expected = {(2, 0): [("background-color", "red")]}
76
+ if f == "highlight_min":
77
+ df = -df
78
+ result = getattr(df.style, f)(**kwargs)._compute().ctx
79
+ assert result == expected
80
+
81
+
82
+ @pytest.mark.parametrize("f", ["highlight_min", "highlight_max"])
83
+ @pytest.mark.parametrize("axis", [None, 0, 1])
84
+ def test_highlight_minmax_nulls(f, axis):
85
+ # GH 42750
86
+ expected = {
87
+ (1, 0): [("background-color", "yellow")],
88
+ (1, 1): [("background-color", "yellow")],
89
+ }
90
+ if axis == 1:
91
+ expected.update({(2, 1): [("background-color", "yellow")]})
92
+
93
+ if f == "highlight_max":
94
+ df = DataFrame({"a": [NA, 1, None], "b": [np.nan, 1, -1]})
95
+ else:
96
+ df = DataFrame({"a": [NA, -1, None], "b": [np.nan, -1, 1]})
97
+
98
+ result = getattr(df.style, f)(axis=axis)._compute().ctx
99
+ assert result == expected
100
+
101
+
102
+ @pytest.mark.parametrize(
103
+ "kwargs",
104
+ [
105
+ {"left": 0, "right": 1}, # test basic range
106
+ {"left": 0, "right": 1, "props": "background-color: yellow"}, # test props
107
+ {"left": -100, "right": 100, "subset": IndexSlice[[0, 1], :]}, # test subset
108
+ {"left": 0, "subset": IndexSlice[[0, 1], :]}, # test no right
109
+ {"right": 1}, # test no left
110
+ {"left": [0, 0, 11], "axis": 0}, # test left as sequence
111
+ {"left": DataFrame({"A": [0, 0, 11], "B": [1, 1, 11]}), "axis": None}, # axis
112
+ {"left": 0, "right": [0, 1], "axis": 1}, # test sequence right
113
+ ],
114
+ )
115
+ def test_highlight_between(styler, kwargs):
116
+ expected = {
117
+ (0, 0): [("background-color", "yellow")],
118
+ (0, 1): [("background-color", "yellow")],
119
+ }
120
+ result = styler.highlight_between(**kwargs)._compute().ctx
121
+ assert result == expected
122
+
123
+
124
+ @pytest.mark.parametrize(
125
+ "arg, map, axis",
126
+ [
127
+ ("left", [1, 2], 0), # 0 axis has 3 elements not 2
128
+ ("left", [1, 2, 3], 1), # 1 axis has 2 elements not 3
129
+ ("left", np.array([[1, 2], [1, 2]]), None), # df is (2,3) not (2,2)
130
+ ("right", [1, 2], 0), # same tests as above for 'right' not 'left'
131
+ ("right", [1, 2, 3], 1), # ..
132
+ ("right", np.array([[1, 2], [1, 2]]), None), # ..
133
+ ],
134
+ )
135
+ def test_highlight_between_raises(arg, styler, map, axis):
136
+ msg = f"supplied '{arg}' is not correct shape"
137
+ with pytest.raises(ValueError, match=msg):
138
+ styler.highlight_between(**{arg: map, "axis": axis})._compute()
139
+
140
+
141
+ def test_highlight_between_raises2(styler):
142
+ msg = "values can be 'both', 'left', 'right', or 'neither'"
143
+ with pytest.raises(ValueError, match=msg):
144
+ styler.highlight_between(inclusive="badstring")._compute()
145
+
146
+ with pytest.raises(ValueError, match=msg):
147
+ styler.highlight_between(inclusive=1)._compute()
148
+
149
+
150
+ @pytest.mark.parametrize(
151
+ "inclusive, expected",
152
+ [
153
+ (
154
+ "both",
155
+ {
156
+ (0, 0): [("background-color", "yellow")],
157
+ (0, 1): [("background-color", "yellow")],
158
+ },
159
+ ),
160
+ ("neither", {}),
161
+ ("left", {(0, 0): [("background-color", "yellow")]}),
162
+ ("right", {(0, 1): [("background-color", "yellow")]}),
163
+ ],
164
+ )
165
+ def test_highlight_between_inclusive(styler, inclusive, expected):
166
+ kwargs = {"left": 0, "right": 1, "subset": IndexSlice[[0, 1], :]}
167
+ result = styler.highlight_between(**kwargs, inclusive=inclusive)._compute()
168
+ assert result.ctx == expected
169
+
170
+
171
+ @pytest.mark.parametrize(
172
+ "kwargs",
173
+ [
174
+ {"q_left": 0.5, "q_right": 1, "axis": 0}, # base case
175
+ {"q_left": 0.5, "q_right": 1, "axis": None}, # test axis
176
+ {"q_left": 0, "q_right": 1, "subset": IndexSlice[2, :]}, # test subset
177
+ {"q_left": 0.5, "axis": 0}, # test no high
178
+ {"q_right": 1, "subset": IndexSlice[2, :], "axis": 1}, # test no low
179
+ {"q_left": 0.5, "axis": 0, "props": "background-color: yellow"}, # tst prop
180
+ ],
181
+ )
182
+ def test_highlight_quantile(styler, kwargs):
183
+ expected = {
184
+ (2, 0): [("background-color", "yellow")],
185
+ (2, 1): [("background-color", "yellow")],
186
+ }
187
+ result = styler.highlight_quantile(**kwargs)._compute().ctx
188
+ assert result == expected
189
+
190
+
191
+ @pytest.mark.parametrize(
192
+ "f,kwargs",
193
+ [
194
+ ("highlight_min", {"axis": 1, "subset": IndexSlice[1, :]}),
195
+ ("highlight_max", {"axis": 0, "subset": [0]}),
196
+ ("highlight_quantile", {"axis": None, "q_left": 0.6, "q_right": 0.8}),
197
+ ("highlight_between", {"subset": [0]}),
198
+ ],
199
+ )
200
+ @pytest.mark.parametrize(
201
+ "df",
202
+ [
203
+ DataFrame([[0, 10], [20, 30]], dtype=int),
204
+ DataFrame([[0, 10], [20, 30]], dtype=float),
205
+ DataFrame([[0, 10], [20, 30]], dtype="datetime64[ns]"),
206
+ DataFrame([[0, 10], [20, 30]], dtype=str),
207
+ DataFrame([[0, 10], [20, 30]], dtype="timedelta64[ns]"),
208
+ ],
209
+ )
210
+ def test_all_highlight_dtypes(f, kwargs, df):
211
+ if f == "highlight_quantile" and isinstance(df.iloc[0, 0], (str)):
212
+ return None # quantile incompatible with str
213
+ if f == "highlight_between":
214
+ kwargs["left"] = df.iloc[1, 0] # set the range low for testing
215
+
216
+ expected = {(1, 0): [("background-color", "yellow")]}
217
+ result = getattr(df.style, f)(**kwargs)._compute().ctx
218
+ assert result == expected
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/test_html.py ADDED
@@ -0,0 +1,1009 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from textwrap import (
2
+ dedent,
3
+ indent,
4
+ )
5
+
6
+ import numpy as np
7
+ import pytest
8
+
9
+ from pandas import (
10
+ DataFrame,
11
+ MultiIndex,
12
+ option_context,
13
+ )
14
+
15
+ jinja2 = pytest.importorskip("jinja2")
16
+ from pandas.io.formats.style import Styler
17
+
18
+
19
+ @pytest.fixture
20
+ def env():
21
+ loader = jinja2.PackageLoader("pandas", "io/formats/templates")
22
+ env = jinja2.Environment(loader=loader, trim_blocks=True)
23
+ return env
24
+
25
+
26
+ @pytest.fixture
27
+ def styler():
28
+ return Styler(DataFrame([[2.61], [2.69]], index=["a", "b"], columns=["A"]))
29
+
30
+
31
+ @pytest.fixture
32
+ def styler_mi():
33
+ midx = MultiIndex.from_product([["a", "b"], ["c", "d"]])
34
+ return Styler(DataFrame(np.arange(16).reshape(4, 4), index=midx, columns=midx))
35
+
36
+
37
+ @pytest.fixture
38
+ def tpl_style(env):
39
+ return env.get_template("html_style.tpl")
40
+
41
+
42
+ @pytest.fixture
43
+ def tpl_table(env):
44
+ return env.get_template("html_table.tpl")
45
+
46
+
47
+ def test_html_template_extends_options():
48
+ # make sure if templates are edited tests are updated as are setup fixtures
49
+ # to understand the dependency
50
+ with open("pandas/io/formats/templates/html.tpl", encoding="utf-8") as file:
51
+ result = file.read()
52
+ assert "{% include html_style_tpl %}" in result
53
+ assert "{% include html_table_tpl %}" in result
54
+
55
+
56
+ def test_exclude_styles(styler):
57
+ result = styler.to_html(exclude_styles=True, doctype_html=True)
58
+ expected = dedent(
59
+ """\
60
+ <!DOCTYPE html>
61
+ <html>
62
+ <head>
63
+ <meta charset="utf-8">
64
+ </head>
65
+ <body>
66
+ <table>
67
+ <thead>
68
+ <tr>
69
+ <th >&nbsp;</th>
70
+ <th >A</th>
71
+ </tr>
72
+ </thead>
73
+ <tbody>
74
+ <tr>
75
+ <th >a</th>
76
+ <td >2.610000</td>
77
+ </tr>
78
+ <tr>
79
+ <th >b</th>
80
+ <td >2.690000</td>
81
+ </tr>
82
+ </tbody>
83
+ </table>
84
+ </body>
85
+ </html>
86
+ """
87
+ )
88
+ assert result == expected
89
+
90
+
91
+ def test_w3_html_format(styler):
92
+ styler.set_uuid("").set_table_styles([{"selector": "th", "props": "att2:v2;"}]).map(
93
+ lambda x: "att1:v1;"
94
+ ).set_table_attributes('class="my-cls1" style="attr3:v3;"').set_td_classes(
95
+ DataFrame(["my-cls2"], index=["a"], columns=["A"])
96
+ ).format(
97
+ "{:.1f}"
98
+ ).set_caption(
99
+ "A comprehensive test"
100
+ )
101
+ expected = dedent(
102
+ """\
103
+ <style type="text/css">
104
+ #T_ th {
105
+ att2: v2;
106
+ }
107
+ #T__row0_col0, #T__row1_col0 {
108
+ att1: v1;
109
+ }
110
+ </style>
111
+ <table id="T_" class="my-cls1" style="attr3:v3;">
112
+ <caption>A comprehensive test</caption>
113
+ <thead>
114
+ <tr>
115
+ <th class="blank level0" >&nbsp;</th>
116
+ <th id="T__level0_col0" class="col_heading level0 col0" >A</th>
117
+ </tr>
118
+ </thead>
119
+ <tbody>
120
+ <tr>
121
+ <th id="T__level0_row0" class="row_heading level0 row0" >a</th>
122
+ <td id="T__row0_col0" class="data row0 col0 my-cls2" >2.6</td>
123
+ </tr>
124
+ <tr>
125
+ <th id="T__level0_row1" class="row_heading level0 row1" >b</th>
126
+ <td id="T__row1_col0" class="data row1 col0" >2.7</td>
127
+ </tr>
128
+ </tbody>
129
+ </table>
130
+ """
131
+ )
132
+ assert expected == styler.to_html()
133
+
134
+
135
+ def test_colspan_w3():
136
+ # GH 36223
137
+ df = DataFrame(data=[[1, 2]], columns=[["l0", "l0"], ["l1a", "l1b"]])
138
+ styler = Styler(df, uuid="_", cell_ids=False)
139
+ assert '<th class="col_heading level0 col0" colspan="2">l0</th>' in styler.to_html()
140
+
141
+
142
+ def test_rowspan_w3():
143
+ # GH 38533
144
+ df = DataFrame(data=[[1, 2]], index=[["l0", "l0"], ["l1a", "l1b"]])
145
+ styler = Styler(df, uuid="_", cell_ids=False)
146
+ assert '<th class="row_heading level0 row0" rowspan="2">l0</th>' in styler.to_html()
147
+
148
+
149
+ def test_styles(styler):
150
+ styler.set_uuid("abc")
151
+ styler.set_table_styles([{"selector": "td", "props": "color: red;"}])
152
+ result = styler.to_html(doctype_html=True)
153
+ expected = dedent(
154
+ """\
155
+ <!DOCTYPE html>
156
+ <html>
157
+ <head>
158
+ <meta charset="utf-8">
159
+ <style type="text/css">
160
+ #T_abc td {
161
+ color: red;
162
+ }
163
+ </style>
164
+ </head>
165
+ <body>
166
+ <table id="T_abc">
167
+ <thead>
168
+ <tr>
169
+ <th class="blank level0" >&nbsp;</th>
170
+ <th id="T_abc_level0_col0" class="col_heading level0 col0" >A</th>
171
+ </tr>
172
+ </thead>
173
+ <tbody>
174
+ <tr>
175
+ <th id="T_abc_level0_row0" class="row_heading level0 row0" >a</th>
176
+ <td id="T_abc_row0_col0" class="data row0 col0" >2.610000</td>
177
+ </tr>
178
+ <tr>
179
+ <th id="T_abc_level0_row1" class="row_heading level0 row1" >b</th>
180
+ <td id="T_abc_row1_col0" class="data row1 col0" >2.690000</td>
181
+ </tr>
182
+ </tbody>
183
+ </table>
184
+ </body>
185
+ </html>
186
+ """
187
+ )
188
+ assert result == expected
189
+
190
+
191
+ def test_doctype(styler):
192
+ result = styler.to_html(doctype_html=False)
193
+ assert "<html>" not in result
194
+ assert "<body>" not in result
195
+ assert "<!DOCTYPE html>" not in result
196
+ assert "<head>" not in result
197
+
198
+
199
+ def test_doctype_encoding(styler):
200
+ with option_context("styler.render.encoding", "ASCII"):
201
+ result = styler.to_html(doctype_html=True)
202
+ assert '<meta charset="ASCII">' in result
203
+ result = styler.to_html(doctype_html=True, encoding="ANSI")
204
+ assert '<meta charset="ANSI">' in result
205
+
206
+
207
+ def test_bold_headers_arg(styler):
208
+ result = styler.to_html(bold_headers=True)
209
+ assert "th {\n font-weight: bold;\n}" in result
210
+ result = styler.to_html()
211
+ assert "th {\n font-weight: bold;\n}" not in result
212
+
213
+
214
+ def test_caption_arg(styler):
215
+ result = styler.to_html(caption="foo bar")
216
+ assert "<caption>foo bar</caption>" in result
217
+ result = styler.to_html()
218
+ assert "<caption>foo bar</caption>" not in result
219
+
220
+
221
+ def test_block_names(tpl_style, tpl_table):
222
+ # catch accidental removal of a block
223
+ expected_style = {
224
+ "before_style",
225
+ "style",
226
+ "table_styles",
227
+ "before_cellstyle",
228
+ "cellstyle",
229
+ }
230
+ expected_table = {
231
+ "before_table",
232
+ "table",
233
+ "caption",
234
+ "thead",
235
+ "tbody",
236
+ "after_table",
237
+ "before_head_rows",
238
+ "head_tr",
239
+ "after_head_rows",
240
+ "before_rows",
241
+ "tr",
242
+ "after_rows",
243
+ }
244
+ result1 = set(tpl_style.blocks)
245
+ assert result1 == expected_style
246
+
247
+ result2 = set(tpl_table.blocks)
248
+ assert result2 == expected_table
249
+
250
+
251
+ def test_from_custom_template_table(tmpdir):
252
+ p = tmpdir.mkdir("tpl").join("myhtml_table.tpl")
253
+ p.write(
254
+ dedent(
255
+ """\
256
+ {% extends "html_table.tpl" %}
257
+ {% block table %}
258
+ <h1>{{custom_title}}</h1>
259
+ {{ super() }}
260
+ {% endblock table %}"""
261
+ )
262
+ )
263
+ result = Styler.from_custom_template(str(tmpdir.join("tpl")), "myhtml_table.tpl")
264
+ assert issubclass(result, Styler)
265
+ assert result.env is not Styler.env
266
+ assert result.template_html_table is not Styler.template_html_table
267
+ styler = result(DataFrame({"A": [1, 2]}))
268
+ assert "<h1>My Title</h1>\n\n\n<table" in styler.to_html(custom_title="My Title")
269
+
270
+
271
+ def test_from_custom_template_style(tmpdir):
272
+ p = tmpdir.mkdir("tpl").join("myhtml_style.tpl")
273
+ p.write(
274
+ dedent(
275
+ """\
276
+ {% extends "html_style.tpl" %}
277
+ {% block style %}
278
+ <link rel="stylesheet" href="mystyle.css">
279
+ {{ super() }}
280
+ {% endblock style %}"""
281
+ )
282
+ )
283
+ result = Styler.from_custom_template(
284
+ str(tmpdir.join("tpl")), html_style="myhtml_style.tpl"
285
+ )
286
+ assert issubclass(result, Styler)
287
+ assert result.env is not Styler.env
288
+ assert result.template_html_style is not Styler.template_html_style
289
+ styler = result(DataFrame({"A": [1, 2]}))
290
+ assert '<link rel="stylesheet" href="mystyle.css">\n\n<style' in styler.to_html()
291
+
292
+
293
+ def test_caption_as_sequence(styler):
294
+ styler.set_caption(("full cap", "short cap"))
295
+ assert "<caption>full cap</caption>" in styler.to_html()
296
+
297
+
298
+ @pytest.mark.parametrize("index", [False, True])
299
+ @pytest.mark.parametrize("columns", [False, True])
300
+ @pytest.mark.parametrize("index_name", [True, False])
301
+ def test_sticky_basic(styler, index, columns, index_name):
302
+ if index_name:
303
+ styler.index.name = "some text"
304
+ if index:
305
+ styler.set_sticky(axis=0)
306
+ if columns:
307
+ styler.set_sticky(axis=1)
308
+
309
+ left_css = (
310
+ "#T_ {0} {{\n position: sticky;\n background-color: inherit;\n"
311
+ " left: 0px;\n z-index: {1};\n}}"
312
+ )
313
+ top_css = (
314
+ "#T_ {0} {{\n position: sticky;\n background-color: inherit;\n"
315
+ " top: {1}px;\n z-index: {2};\n{3}}}"
316
+ )
317
+
318
+ res = styler.set_uuid("").to_html()
319
+
320
+ # test index stickys over thead and tbody
321
+ assert (left_css.format("thead tr th:nth-child(1)", "3 !important") in res) is index
322
+ assert (left_css.format("tbody tr th:nth-child(1)", "1") in res) is index
323
+
324
+ # test column stickys including if name row
325
+ assert (
326
+ top_css.format("thead tr:nth-child(1) th", "0", "2", " height: 25px;\n") in res
327
+ ) is (columns and index_name)
328
+ assert (
329
+ top_css.format("thead tr:nth-child(2) th", "25", "2", " height: 25px;\n")
330
+ in res
331
+ ) is (columns and index_name)
332
+ assert (top_css.format("thead tr:nth-child(1) th", "0", "2", "") in res) is (
333
+ columns and not index_name
334
+ )
335
+
336
+
337
+ @pytest.mark.parametrize("index", [False, True])
338
+ @pytest.mark.parametrize("columns", [False, True])
339
+ def test_sticky_mi(styler_mi, index, columns):
340
+ if index:
341
+ styler_mi.set_sticky(axis=0)
342
+ if columns:
343
+ styler_mi.set_sticky(axis=1)
344
+
345
+ left_css = (
346
+ "#T_ {0} {{\n position: sticky;\n background-color: inherit;\n"
347
+ " left: {1}px;\n min-width: 75px;\n max-width: 75px;\n z-index: {2};\n}}"
348
+ )
349
+ top_css = (
350
+ "#T_ {0} {{\n position: sticky;\n background-color: inherit;\n"
351
+ " top: {1}px;\n height: 25px;\n z-index: {2};\n}}"
352
+ )
353
+
354
+ res = styler_mi.set_uuid("").to_html()
355
+
356
+ # test the index stickys for thead and tbody over both levels
357
+ assert (
358
+ left_css.format("thead tr th:nth-child(1)", "0", "3 !important") in res
359
+ ) is index
360
+ assert (left_css.format("tbody tr th.level0", "0", "1") in res) is index
361
+ assert (
362
+ left_css.format("thead tr th:nth-child(2)", "75", "3 !important") in res
363
+ ) is index
364
+ assert (left_css.format("tbody tr th.level1", "75", "1") in res) is index
365
+
366
+ # test the column stickys for each level row
367
+ assert (top_css.format("thead tr:nth-child(1) th", "0", "2") in res) is columns
368
+ assert (top_css.format("thead tr:nth-child(2) th", "25", "2") in res) is columns
369
+
370
+
371
+ @pytest.mark.parametrize("index", [False, True])
372
+ @pytest.mark.parametrize("columns", [False, True])
373
+ @pytest.mark.parametrize("levels", [[1], ["one"], "one"])
374
+ def test_sticky_levels(styler_mi, index, columns, levels):
375
+ styler_mi.index.names, styler_mi.columns.names = ["zero", "one"], ["zero", "one"]
376
+ if index:
377
+ styler_mi.set_sticky(axis=0, levels=levels)
378
+ if columns:
379
+ styler_mi.set_sticky(axis=1, levels=levels)
380
+
381
+ left_css = (
382
+ "#T_ {0} {{\n position: sticky;\n background-color: inherit;\n"
383
+ " left: {1}px;\n min-width: 75px;\n max-width: 75px;\n z-index: {2};\n}}"
384
+ )
385
+ top_css = (
386
+ "#T_ {0} {{\n position: sticky;\n background-color: inherit;\n"
387
+ " top: {1}px;\n height: 25px;\n z-index: {2};\n}}"
388
+ )
389
+
390
+ res = styler_mi.set_uuid("").to_html()
391
+
392
+ # test no sticking of level0
393
+ assert "#T_ thead tr th:nth-child(1)" not in res
394
+ assert "#T_ tbody tr th.level0" not in res
395
+ assert "#T_ thead tr:nth-child(1) th" not in res
396
+
397
+ # test sticking level1
398
+ assert (
399
+ left_css.format("thead tr th:nth-child(2)", "0", "3 !important") in res
400
+ ) is index
401
+ assert (left_css.format("tbody tr th.level1", "0", "1") in res) is index
402
+ assert (top_css.format("thead tr:nth-child(2) th", "0", "2") in res) is columns
403
+
404
+
405
+ def test_sticky_raises(styler):
406
+ with pytest.raises(ValueError, match="No axis named bad for object type DataFrame"):
407
+ styler.set_sticky(axis="bad")
408
+
409
+
410
+ @pytest.mark.parametrize(
411
+ "sparse_index, sparse_columns",
412
+ [(True, True), (True, False), (False, True), (False, False)],
413
+ )
414
+ def test_sparse_options(sparse_index, sparse_columns):
415
+ cidx = MultiIndex.from_tuples([("Z", "a"), ("Z", "b"), ("Y", "c")])
416
+ ridx = MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("B", "c")])
417
+ df = DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], index=ridx, columns=cidx)
418
+ styler = df.style
419
+
420
+ default_html = styler.to_html() # defaults under pd.options to (True , True)
421
+
422
+ with option_context(
423
+ "styler.sparse.index", sparse_index, "styler.sparse.columns", sparse_columns
424
+ ):
425
+ html1 = styler.to_html()
426
+ assert (html1 == default_html) is (sparse_index and sparse_columns)
427
+ html2 = styler.to_html(sparse_index=sparse_index, sparse_columns=sparse_columns)
428
+ assert html1 == html2
429
+
430
+
431
+ @pytest.mark.parametrize("index", [True, False])
432
+ @pytest.mark.parametrize("columns", [True, False])
433
+ def test_map_header_cell_ids(styler, index, columns):
434
+ # GH 41893
435
+ func = lambda v: "attr: val;"
436
+ styler.uuid, styler.cell_ids = "", False
437
+ if index:
438
+ styler.map_index(func, axis="index")
439
+ if columns:
440
+ styler.map_index(func, axis="columns")
441
+
442
+ result = styler.to_html()
443
+
444
+ # test no data cell ids
445
+ assert '<td class="data row0 col0" >2.610000</td>' in result
446
+ assert '<td class="data row1 col0" >2.690000</td>' in result
447
+
448
+ # test index header ids where needed and css styles
449
+ assert (
450
+ '<th id="T__level0_row0" class="row_heading level0 row0" >a</th>' in result
451
+ ) is index
452
+ assert (
453
+ '<th id="T__level0_row1" class="row_heading level0 row1" >b</th>' in result
454
+ ) is index
455
+ assert ("#T__level0_row0, #T__level0_row1 {\n attr: val;\n}" in result) is index
456
+
457
+ # test column header ids where needed and css styles
458
+ assert (
459
+ '<th id="T__level0_col0" class="col_heading level0 col0" >A</th>' in result
460
+ ) is columns
461
+ assert ("#T__level0_col0 {\n attr: val;\n}" in result) is columns
462
+
463
+
464
+ @pytest.mark.parametrize("rows", [True, False])
465
+ @pytest.mark.parametrize("cols", [True, False])
466
+ def test_maximums(styler_mi, rows, cols):
467
+ result = styler_mi.to_html(
468
+ max_rows=2 if rows else None,
469
+ max_columns=2 if cols else None,
470
+ )
471
+
472
+ assert ">5</td>" in result # [[0,1], [4,5]] always visible
473
+ assert (">8</td>" in result) is not rows # first trimmed vertical element
474
+ assert (">2</td>" in result) is not cols # first trimmed horizontal element
475
+
476
+
477
+ def test_replaced_css_class_names():
478
+ css = {
479
+ "row_heading": "ROWHEAD",
480
+ # "col_heading": "COLHEAD",
481
+ "index_name": "IDXNAME",
482
+ # "col": "COL",
483
+ "row": "ROW",
484
+ # "col_trim": "COLTRIM",
485
+ "row_trim": "ROWTRIM",
486
+ "level": "LEVEL",
487
+ "data": "DATA",
488
+ "blank": "BLANK",
489
+ }
490
+ midx = MultiIndex.from_product([["a", "b"], ["c", "d"]])
491
+ styler_mi = Styler(
492
+ DataFrame(np.arange(16).reshape(4, 4), index=midx, columns=midx),
493
+ uuid_len=0,
494
+ ).set_table_styles(css_class_names=css)
495
+ styler_mi.index.names = ["n1", "n2"]
496
+ styler_mi.hide(styler_mi.index[1:], axis=0)
497
+ styler_mi.hide(styler_mi.columns[1:], axis=1)
498
+ styler_mi.map_index(lambda v: "color: red;", axis=0)
499
+ styler_mi.map_index(lambda v: "color: green;", axis=1)
500
+ styler_mi.map(lambda v: "color: blue;")
501
+ expected = dedent(
502
+ """\
503
+ <style type="text/css">
504
+ #T__ROW0_col0 {
505
+ color: blue;
506
+ }
507
+ #T__LEVEL0_ROW0, #T__LEVEL1_ROW0 {
508
+ color: red;
509
+ }
510
+ #T__LEVEL0_col0, #T__LEVEL1_col0 {
511
+ color: green;
512
+ }
513
+ </style>
514
+ <table id="T_">
515
+ <thead>
516
+ <tr>
517
+ <th class="BLANK" >&nbsp;</th>
518
+ <th class="IDXNAME LEVEL0" >n1</th>
519
+ <th id="T__LEVEL0_col0" class="col_heading LEVEL0 col0" >a</th>
520
+ </tr>
521
+ <tr>
522
+ <th class="BLANK" >&nbsp;</th>
523
+ <th class="IDXNAME LEVEL1" >n2</th>
524
+ <th id="T__LEVEL1_col0" class="col_heading LEVEL1 col0" >c</th>
525
+ </tr>
526
+ <tr>
527
+ <th class="IDXNAME LEVEL0" >n1</th>
528
+ <th class="IDXNAME LEVEL1" >n2</th>
529
+ <th class="BLANK col0" >&nbsp;</th>
530
+ </tr>
531
+ </thead>
532
+ <tbody>
533
+ <tr>
534
+ <th id="T__LEVEL0_ROW0" class="ROWHEAD LEVEL0 ROW0" >a</th>
535
+ <th id="T__LEVEL1_ROW0" class="ROWHEAD LEVEL1 ROW0" >c</th>
536
+ <td id="T__ROW0_col0" class="DATA ROW0 col0" >0</td>
537
+ </tr>
538
+ </tbody>
539
+ </table>
540
+ """
541
+ )
542
+ result = styler_mi.to_html()
543
+ assert result == expected
544
+
545
+
546
+ def test_include_css_style_rules_only_for_visible_cells(styler_mi):
547
+ # GH 43619
548
+ result = (
549
+ styler_mi.set_uuid("")
550
+ .map(lambda v: "color: blue;")
551
+ .hide(styler_mi.data.columns[1:], axis="columns")
552
+ .hide(styler_mi.data.index[1:], axis="index")
553
+ .to_html()
554
+ )
555
+ expected_styles = dedent(
556
+ """\
557
+ <style type="text/css">
558
+ #T__row0_col0 {
559
+ color: blue;
560
+ }
561
+ </style>
562
+ """
563
+ )
564
+ assert expected_styles in result
565
+
566
+
567
+ def test_include_css_style_rules_only_for_visible_index_labels(styler_mi):
568
+ # GH 43619
569
+ result = (
570
+ styler_mi.set_uuid("")
571
+ .map_index(lambda v: "color: blue;", axis="index")
572
+ .hide(styler_mi.data.columns, axis="columns")
573
+ .hide(styler_mi.data.index[1:], axis="index")
574
+ .to_html()
575
+ )
576
+ expected_styles = dedent(
577
+ """\
578
+ <style type="text/css">
579
+ #T__level0_row0, #T__level1_row0 {
580
+ color: blue;
581
+ }
582
+ </style>
583
+ """
584
+ )
585
+ assert expected_styles in result
586
+
587
+
588
+ def test_include_css_style_rules_only_for_visible_column_labels(styler_mi):
589
+ # GH 43619
590
+ result = (
591
+ styler_mi.set_uuid("")
592
+ .map_index(lambda v: "color: blue;", axis="columns")
593
+ .hide(styler_mi.data.columns[1:], axis="columns")
594
+ .hide(styler_mi.data.index, axis="index")
595
+ .to_html()
596
+ )
597
+ expected_styles = dedent(
598
+ """\
599
+ <style type="text/css">
600
+ #T__level0_col0, #T__level1_col0 {
601
+ color: blue;
602
+ }
603
+ </style>
604
+ """
605
+ )
606
+ assert expected_styles in result
607
+
608
+
609
+ def test_hiding_index_columns_multiindex_alignment():
610
+ # gh 43644
611
+ midx = MultiIndex.from_product(
612
+ [["i0", "j0"], ["i1"], ["i2", "j2"]], names=["i-0", "i-1", "i-2"]
613
+ )
614
+ cidx = MultiIndex.from_product(
615
+ [["c0"], ["c1", "d1"], ["c2", "d2"]], names=["c-0", "c-1", "c-2"]
616
+ )
617
+ df = DataFrame(np.arange(16).reshape(4, 4), index=midx, columns=cidx)
618
+ styler = Styler(df, uuid_len=0)
619
+ styler.hide(level=1, axis=0).hide(level=0, axis=1)
620
+ styler.hide([("j0", "i1", "j2")], axis=0)
621
+ styler.hide([("c0", "d1", "d2")], axis=1)
622
+ result = styler.to_html()
623
+ expected = dedent(
624
+ """\
625
+ <style type="text/css">
626
+ </style>
627
+ <table id="T_">
628
+ <thead>
629
+ <tr>
630
+ <th class="blank" >&nbsp;</th>
631
+ <th class="index_name level1" >c-1</th>
632
+ <th id="T__level1_col0" class="col_heading level1 col0" colspan="2">c1</th>
633
+ <th id="T__level1_col2" class="col_heading level1 col2" >d1</th>
634
+ </tr>
635
+ <tr>
636
+ <th class="blank" >&nbsp;</th>
637
+ <th class="index_name level2" >c-2</th>
638
+ <th id="T__level2_col0" class="col_heading level2 col0" >c2</th>
639
+ <th id="T__level2_col1" class="col_heading level2 col1" >d2</th>
640
+ <th id="T__level2_col2" class="col_heading level2 col2" >c2</th>
641
+ </tr>
642
+ <tr>
643
+ <th class="index_name level0" >i-0</th>
644
+ <th class="index_name level2" >i-2</th>
645
+ <th class="blank col0" >&nbsp;</th>
646
+ <th class="blank col1" >&nbsp;</th>
647
+ <th class="blank col2" >&nbsp;</th>
648
+ </tr>
649
+ </thead>
650
+ <tbody>
651
+ <tr>
652
+ <th id="T__level0_row0" class="row_heading level0 row0" rowspan="2">i0</th>
653
+ <th id="T__level2_row0" class="row_heading level2 row0" >i2</th>
654
+ <td id="T__row0_col0" class="data row0 col0" >0</td>
655
+ <td id="T__row0_col1" class="data row0 col1" >1</td>
656
+ <td id="T__row0_col2" class="data row0 col2" >2</td>
657
+ </tr>
658
+ <tr>
659
+ <th id="T__level2_row1" class="row_heading level2 row1" >j2</th>
660
+ <td id="T__row1_col0" class="data row1 col0" >4</td>
661
+ <td id="T__row1_col1" class="data row1 col1" >5</td>
662
+ <td id="T__row1_col2" class="data row1 col2" >6</td>
663
+ </tr>
664
+ <tr>
665
+ <th id="T__level0_row2" class="row_heading level0 row2" >j0</th>
666
+ <th id="T__level2_row2" class="row_heading level2 row2" >i2</th>
667
+ <td id="T__row2_col0" class="data row2 col0" >8</td>
668
+ <td id="T__row2_col1" class="data row2 col1" >9</td>
669
+ <td id="T__row2_col2" class="data row2 col2" >10</td>
670
+ </tr>
671
+ </tbody>
672
+ </table>
673
+ """
674
+ )
675
+ assert result == expected
676
+
677
+
678
+ def test_hiding_index_columns_multiindex_trimming():
679
+ # gh 44272
680
+ df = DataFrame(np.arange(64).reshape(8, 8))
681
+ df.columns = MultiIndex.from_product([[0, 1, 2, 3], [0, 1]])
682
+ df.index = MultiIndex.from_product([[0, 1, 2, 3], [0, 1]])
683
+ df.index.names, df.columns.names = ["a", "b"], ["c", "d"]
684
+ styler = Styler(df, cell_ids=False, uuid_len=0)
685
+ styler.hide([(0, 0), (0, 1), (1, 0)], axis=1).hide([(0, 0), (0, 1), (1, 0)], axis=0)
686
+ with option_context("styler.render.max_rows", 4, "styler.render.max_columns", 4):
687
+ result = styler.to_html()
688
+
689
+ expected = dedent(
690
+ """\
691
+ <style type="text/css">
692
+ </style>
693
+ <table id="T_">
694
+ <thead>
695
+ <tr>
696
+ <th class="blank" >&nbsp;</th>
697
+ <th class="index_name level0" >c</th>
698
+ <th class="col_heading level0 col3" >1</th>
699
+ <th class="col_heading level0 col4" colspan="2">2</th>
700
+ <th class="col_heading level0 col6" >3</th>
701
+ </tr>
702
+ <tr>
703
+ <th class="blank" >&nbsp;</th>
704
+ <th class="index_name level1" >d</th>
705
+ <th class="col_heading level1 col3" >1</th>
706
+ <th class="col_heading level1 col4" >0</th>
707
+ <th class="col_heading level1 col5" >1</th>
708
+ <th class="col_heading level1 col6" >0</th>
709
+ <th class="col_heading level1 col_trim" >...</th>
710
+ </tr>
711
+ <tr>
712
+ <th class="index_name level0" >a</th>
713
+ <th class="index_name level1" >b</th>
714
+ <th class="blank col3" >&nbsp;</th>
715
+ <th class="blank col4" >&nbsp;</th>
716
+ <th class="blank col5" >&nbsp;</th>
717
+ <th class="blank col6" >&nbsp;</th>
718
+ <th class="blank col7 col_trim" >&nbsp;</th>
719
+ </tr>
720
+ </thead>
721
+ <tbody>
722
+ <tr>
723
+ <th class="row_heading level0 row3" >1</th>
724
+ <th class="row_heading level1 row3" >1</th>
725
+ <td class="data row3 col3" >27</td>
726
+ <td class="data row3 col4" >28</td>
727
+ <td class="data row3 col5" >29</td>
728
+ <td class="data row3 col6" >30</td>
729
+ <td class="data row3 col_trim" >...</td>
730
+ </tr>
731
+ <tr>
732
+ <th class="row_heading level0 row4" rowspan="2">2</th>
733
+ <th class="row_heading level1 row4" >0</th>
734
+ <td class="data row4 col3" >35</td>
735
+ <td class="data row4 col4" >36</td>
736
+ <td class="data row4 col5" >37</td>
737
+ <td class="data row4 col6" >38</td>
738
+ <td class="data row4 col_trim" >...</td>
739
+ </tr>
740
+ <tr>
741
+ <th class="row_heading level1 row5" >1</th>
742
+ <td class="data row5 col3" >43</td>
743
+ <td class="data row5 col4" >44</td>
744
+ <td class="data row5 col5" >45</td>
745
+ <td class="data row5 col6" >46</td>
746
+ <td class="data row5 col_trim" >...</td>
747
+ </tr>
748
+ <tr>
749
+ <th class="row_heading level0 row6" >3</th>
750
+ <th class="row_heading level1 row6" >0</th>
751
+ <td class="data row6 col3" >51</td>
752
+ <td class="data row6 col4" >52</td>
753
+ <td class="data row6 col5" >53</td>
754
+ <td class="data row6 col6" >54</td>
755
+ <td class="data row6 col_trim" >...</td>
756
+ </tr>
757
+ <tr>
758
+ <th class="row_heading level0 row_trim" >...</th>
759
+ <th class="row_heading level1 row_trim" >...</th>
760
+ <td class="data col3 row_trim" >...</td>
761
+ <td class="data col4 row_trim" >...</td>
762
+ <td class="data col5 row_trim" >...</td>
763
+ <td class="data col6 row_trim" >...</td>
764
+ <td class="data row_trim col_trim" >...</td>
765
+ </tr>
766
+ </tbody>
767
+ </table>
768
+ """
769
+ )
770
+
771
+ assert result == expected
772
+
773
+
774
+ @pytest.mark.parametrize("type", ["data", "index"])
775
+ @pytest.mark.parametrize(
776
+ "text, exp, found",
777
+ [
778
+ ("no link, just text", False, ""),
779
+ ("subdomain not www: sub.web.com", False, ""),
780
+ ("www subdomain: www.web.com other", True, "www.web.com"),
781
+ ("scheme full structure: http://www.web.com", True, "http://www.web.com"),
782
+ ("scheme no top-level: http://www.web", True, "http://www.web"),
783
+ ("no scheme, no top-level: www.web", False, "www.web"),
784
+ ("https scheme: https://www.web.com", True, "https://www.web.com"),
785
+ ("ftp scheme: ftp://www.web", True, "ftp://www.web"),
786
+ ("ftps scheme: ftps://www.web", True, "ftps://www.web"),
787
+ ("subdirectories: www.web.com/directory", True, "www.web.com/directory"),
788
+ ("Multiple domains: www.1.2.3.4", True, "www.1.2.3.4"),
789
+ ("with port: http://web.com:80", True, "http://web.com:80"),
790
+ (
791
+ "full net_loc scheme: http://user:[email protected]",
792
+ True,
793
+ "http://user:[email protected]",
794
+ ),
795
+ (
796
+ "with valid special chars: http://web.com/,.':;~!@#$*()[]",
797
+ True,
798
+ "http://web.com/,.':;~!@#$*()[]",
799
+ ),
800
+ ],
801
+ )
802
+ def test_rendered_links(type, text, exp, found):
803
+ if type == "data":
804
+ df = DataFrame([text])
805
+ styler = df.style.format(hyperlinks="html")
806
+ else:
807
+ df = DataFrame([0], index=[text])
808
+ styler = df.style.format_index(hyperlinks="html")
809
+
810
+ rendered = f'<a href="{found}" target="_blank">{found}</a>'
811
+ result = styler.to_html()
812
+ assert (rendered in result) is exp
813
+ assert (text in result) is not exp # test conversion done when expected and not
814
+
815
+
816
+ def test_multiple_rendered_links():
817
+ links = ("www.a.b", "http://a.c", "https://a.d", "ftp://a.e")
818
+ # pylint: disable-next=consider-using-f-string
819
+ df = DataFrame(["text {} {} text {} {}".format(*links)])
820
+ result = df.style.format(hyperlinks="html").to_html()
821
+ href = '<a href="{0}" target="_blank">{0}</a>'
822
+ for link in links:
823
+ assert href.format(link) in result
824
+ assert href.format("text") not in result
825
+
826
+
827
+ def test_concat(styler):
828
+ other = styler.data.agg(["mean"]).style
829
+ styler.concat(other).set_uuid("X")
830
+ result = styler.to_html()
831
+ fp = "foot0_"
832
+ expected = dedent(
833
+ f"""\
834
+ <tr>
835
+ <th id="T_X_level0_row1" class="row_heading level0 row1" >b</th>
836
+ <td id="T_X_row1_col0" class="data row1 col0" >2.690000</td>
837
+ </tr>
838
+ <tr>
839
+ <th id="T_X_level0_{fp}row0" class="{fp}row_heading level0 {fp}row0" >mean</th>
840
+ <td id="T_X_{fp}row0_col0" class="{fp}data {fp}row0 col0" >2.650000</td>
841
+ </tr>
842
+ </tbody>
843
+ </table>
844
+ """
845
+ )
846
+ assert expected in result
847
+
848
+
849
+ def test_concat_recursion(styler):
850
+ df = styler.data
851
+ styler1 = styler
852
+ styler2 = Styler(df.agg(["mean"]), precision=3)
853
+ styler3 = Styler(df.agg(["mean"]), precision=4)
854
+ styler1.concat(styler2.concat(styler3)).set_uuid("X")
855
+ result = styler.to_html()
856
+ # notice that the second concat (last <tr> of the output html),
857
+ # there are two `foot_` in the id and class
858
+ fp1 = "foot0_"
859
+ fp2 = "foot0_foot0_"
860
+ expected = dedent(
861
+ f"""\
862
+ <tr>
863
+ <th id="T_X_level0_row1" class="row_heading level0 row1" >b</th>
864
+ <td id="T_X_row1_col0" class="data row1 col0" >2.690000</td>
865
+ </tr>
866
+ <tr>
867
+ <th id="T_X_level0_{fp1}row0" class="{fp1}row_heading level0 {fp1}row0" >mean</th>
868
+ <td id="T_X_{fp1}row0_col0" class="{fp1}data {fp1}row0 col0" >2.650</td>
869
+ </tr>
870
+ <tr>
871
+ <th id="T_X_level0_{fp2}row0" class="{fp2}row_heading level0 {fp2}row0" >mean</th>
872
+ <td id="T_X_{fp2}row0_col0" class="{fp2}data {fp2}row0 col0" >2.6500</td>
873
+ </tr>
874
+ </tbody>
875
+ </table>
876
+ """
877
+ )
878
+ assert expected in result
879
+
880
+
881
+ def test_concat_chain(styler):
882
+ df = styler.data
883
+ styler1 = styler
884
+ styler2 = Styler(df.agg(["mean"]), precision=3)
885
+ styler3 = Styler(df.agg(["mean"]), precision=4)
886
+ styler1.concat(styler2).concat(styler3).set_uuid("X")
887
+ result = styler.to_html()
888
+ fp1 = "foot0_"
889
+ fp2 = "foot1_"
890
+ expected = dedent(
891
+ f"""\
892
+ <tr>
893
+ <th id="T_X_level0_row1" class="row_heading level0 row1" >b</th>
894
+ <td id="T_X_row1_col0" class="data row1 col0" >2.690000</td>
895
+ </tr>
896
+ <tr>
897
+ <th id="T_X_level0_{fp1}row0" class="{fp1}row_heading level0 {fp1}row0" >mean</th>
898
+ <td id="T_X_{fp1}row0_col0" class="{fp1}data {fp1}row0 col0" >2.650</td>
899
+ </tr>
900
+ <tr>
901
+ <th id="T_X_level0_{fp2}row0" class="{fp2}row_heading level0 {fp2}row0" >mean</th>
902
+ <td id="T_X_{fp2}row0_col0" class="{fp2}data {fp2}row0 col0" >2.6500</td>
903
+ </tr>
904
+ </tbody>
905
+ </table>
906
+ """
907
+ )
908
+ assert expected in result
909
+
910
+
911
+ def test_concat_combined():
912
+ def html_lines(foot_prefix: str):
913
+ assert foot_prefix.endswith("_") or foot_prefix == ""
914
+ fp = foot_prefix
915
+ return indent(
916
+ dedent(
917
+ f"""\
918
+ <tr>
919
+ <th id="T_X_level0_{fp}row0" class="{fp}row_heading level0 {fp}row0" >a</th>
920
+ <td id="T_X_{fp}row0_col0" class="{fp}data {fp}row0 col0" >2.610000</td>
921
+ </tr>
922
+ <tr>
923
+ <th id="T_X_level0_{fp}row1" class="{fp}row_heading level0 {fp}row1" >b</th>
924
+ <td id="T_X_{fp}row1_col0" class="{fp}data {fp}row1 col0" >2.690000</td>
925
+ </tr>
926
+ """
927
+ ),
928
+ prefix=" " * 4,
929
+ )
930
+
931
+ df = DataFrame([[2.61], [2.69]], index=["a", "b"], columns=["A"])
932
+ s1 = df.style.highlight_max(color="red")
933
+ s2 = df.style.highlight_max(color="green")
934
+ s3 = df.style.highlight_max(color="blue")
935
+ s4 = df.style.highlight_max(color="yellow")
936
+
937
+ result = s1.concat(s2).concat(s3.concat(s4)).set_uuid("X").to_html()
938
+ expected_css = dedent(
939
+ """\
940
+ <style type="text/css">
941
+ #T_X_row1_col0 {
942
+ background-color: red;
943
+ }
944
+ #T_X_foot0_row1_col0 {
945
+ background-color: green;
946
+ }
947
+ #T_X_foot1_row1_col0 {
948
+ background-color: blue;
949
+ }
950
+ #T_X_foot1_foot0_row1_col0 {
951
+ background-color: yellow;
952
+ }
953
+ </style>
954
+ """
955
+ )
956
+ expected_table = (
957
+ dedent(
958
+ """\
959
+ <table id="T_X">
960
+ <thead>
961
+ <tr>
962
+ <th class="blank level0" >&nbsp;</th>
963
+ <th id="T_X_level0_col0" class="col_heading level0 col0" >A</th>
964
+ </tr>
965
+ </thead>
966
+ <tbody>
967
+ """
968
+ )
969
+ + html_lines("")
970
+ + html_lines("foot0_")
971
+ + html_lines("foot1_")
972
+ + html_lines("foot1_foot0_")
973
+ + dedent(
974
+ """\
975
+ </tbody>
976
+ </table>
977
+ """
978
+ )
979
+ )
980
+ assert expected_css + expected_table == result
981
+
982
+
983
+ def test_to_html_na_rep_non_scalar_data(datapath):
984
+ # GH47103
985
+ df = DataFrame([{"a": 1, "b": [1, 2, 3], "c": np.nan}])
986
+ result = df.style.format(na_rep="-").to_html(table_uuid="test")
987
+ expected = """\
988
+ <style type="text/css">
989
+ </style>
990
+ <table id="T_test">
991
+ <thead>
992
+ <tr>
993
+ <th class="blank level0" >&nbsp;</th>
994
+ <th id="T_test_level0_col0" class="col_heading level0 col0" >a</th>
995
+ <th id="T_test_level0_col1" class="col_heading level0 col1" >b</th>
996
+ <th id="T_test_level0_col2" class="col_heading level0 col2" >c</th>
997
+ </tr>
998
+ </thead>
999
+ <tbody>
1000
+ <tr>
1001
+ <th id="T_test_level0_row0" class="row_heading level0 row0" >0</th>
1002
+ <td id="T_test_row0_col0" class="data row0 col0" >1</td>
1003
+ <td id="T_test_row0_col1" class="data row0 col1" >[1, 2, 3]</td>
1004
+ <td id="T_test_row0_col2" class="data row0 col2" >-</td>
1005
+ </tr>
1006
+ </tbody>
1007
+ </table>
1008
+ """
1009
+ assert result == expected
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/test_matplotlib.py ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gc
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ from pandas import (
7
+ DataFrame,
8
+ IndexSlice,
9
+ Series,
10
+ )
11
+
12
+ pytest.importorskip("matplotlib")
13
+ pytest.importorskip("jinja2")
14
+
15
+ import matplotlib as mpl
16
+
17
+ from pandas.io.formats.style import Styler
18
+
19
+
20
+ @pytest.fixture(autouse=True)
21
+ def mpl_cleanup():
22
+ # matplotlib/testing/decorators.py#L24
23
+ # 1) Resets units registry
24
+ # 2) Resets rc_context
25
+ # 3) Closes all figures
26
+ mpl = pytest.importorskip("matplotlib")
27
+ mpl_units = pytest.importorskip("matplotlib.units")
28
+ plt = pytest.importorskip("matplotlib.pyplot")
29
+ orig_units_registry = mpl_units.registry.copy()
30
+ with mpl.rc_context():
31
+ mpl.use("template")
32
+ yield
33
+ mpl_units.registry.clear()
34
+ mpl_units.registry.update(orig_units_registry)
35
+ plt.close("all")
36
+ # https://matplotlib.org/stable/users/prev_whats_new/whats_new_3.6.0.html#garbage-collection-is-no-longer-run-on-figure-close # noqa: E501
37
+ gc.collect(1)
38
+
39
+
40
+ @pytest.fixture
41
+ def df():
42
+ return DataFrame([[1, 2], [2, 4]], columns=["A", "B"])
43
+
44
+
45
+ @pytest.fixture
46
+ def styler(df):
47
+ return Styler(df, uuid_len=0)
48
+
49
+
50
+ @pytest.fixture
51
+ def df_blank():
52
+ return DataFrame([[0, 0], [0, 0]], columns=["A", "B"], index=["X", "Y"])
53
+
54
+
55
+ @pytest.fixture
56
+ def styler_blank(df_blank):
57
+ return Styler(df_blank, uuid_len=0)
58
+
59
+
60
+ @pytest.mark.parametrize("f", ["background_gradient", "text_gradient"])
61
+ def test_function_gradient(styler, f):
62
+ for c_map in [None, "YlOrRd"]:
63
+ result = getattr(styler, f)(cmap=c_map)._compute().ctx
64
+ assert all("#" in x[0][1] for x in result.values())
65
+ assert result[(0, 0)] == result[(0, 1)]
66
+ assert result[(1, 0)] == result[(1, 1)]
67
+
68
+
69
+ @pytest.mark.parametrize("f", ["background_gradient", "text_gradient"])
70
+ def test_background_gradient_color(styler, f):
71
+ result = getattr(styler, f)(subset=IndexSlice[1, "A"])._compute().ctx
72
+ if f == "background_gradient":
73
+ assert result[(1, 0)] == [("background-color", "#fff7fb"), ("color", "#000000")]
74
+ elif f == "text_gradient":
75
+ assert result[(1, 0)] == [("color", "#fff7fb")]
76
+
77
+
78
+ @pytest.mark.parametrize(
79
+ "axis, expected",
80
+ [
81
+ (0, ["low", "low", "high", "high"]),
82
+ (1, ["low", "high", "low", "high"]),
83
+ (None, ["low", "mid", "mid", "high"]),
84
+ ],
85
+ )
86
+ @pytest.mark.parametrize("f", ["background_gradient", "text_gradient"])
87
+ def test_background_gradient_axis(styler, axis, expected, f):
88
+ if f == "background_gradient":
89
+ colors = {
90
+ "low": [("background-color", "#f7fbff"), ("color", "#000000")],
91
+ "mid": [("background-color", "#abd0e6"), ("color", "#000000")],
92
+ "high": [("background-color", "#08306b"), ("color", "#f1f1f1")],
93
+ }
94
+ elif f == "text_gradient":
95
+ colors = {
96
+ "low": [("color", "#f7fbff")],
97
+ "mid": [("color", "#abd0e6")],
98
+ "high": [("color", "#08306b")],
99
+ }
100
+ result = getattr(styler, f)(cmap="Blues", axis=axis)._compute().ctx
101
+ for i, cell in enumerate([(0, 0), (0, 1), (1, 0), (1, 1)]):
102
+ assert result[cell] == colors[expected[i]]
103
+
104
+
105
+ @pytest.mark.parametrize(
106
+ "cmap, expected",
107
+ [
108
+ (
109
+ "PuBu",
110
+ {
111
+ (4, 5): [("background-color", "#86b0d3"), ("color", "#000000")],
112
+ (4, 6): [("background-color", "#83afd3"), ("color", "#f1f1f1")],
113
+ },
114
+ ),
115
+ (
116
+ "YlOrRd",
117
+ {
118
+ (4, 8): [("background-color", "#fd913e"), ("color", "#000000")],
119
+ (4, 9): [("background-color", "#fd8f3d"), ("color", "#f1f1f1")],
120
+ },
121
+ ),
122
+ (
123
+ None,
124
+ {
125
+ (7, 0): [("background-color", "#48c16e"), ("color", "#f1f1f1")],
126
+ (7, 1): [("background-color", "#4cc26c"), ("color", "#000000")],
127
+ },
128
+ ),
129
+ ],
130
+ )
131
+ def test_text_color_threshold(cmap, expected):
132
+ # GH 39888
133
+ df = DataFrame(np.arange(100).reshape(10, 10))
134
+ result = df.style.background_gradient(cmap=cmap, axis=None)._compute().ctx
135
+ for k in expected.keys():
136
+ assert result[k] == expected[k]
137
+
138
+
139
+ def test_background_gradient_vmin_vmax():
140
+ # GH 12145
141
+ df = DataFrame(range(5))
142
+ ctx = df.style.background_gradient(vmin=1, vmax=3)._compute().ctx
143
+ assert ctx[(0, 0)] == ctx[(1, 0)]
144
+ assert ctx[(4, 0)] == ctx[(3, 0)]
145
+
146
+
147
+ def test_background_gradient_int64():
148
+ # GH 28869
149
+ df1 = Series(range(3)).to_frame()
150
+ df2 = Series(range(3), dtype="Int64").to_frame()
151
+ ctx1 = df1.style.background_gradient()._compute().ctx
152
+ ctx2 = df2.style.background_gradient()._compute().ctx
153
+ assert ctx2[(0, 0)] == ctx1[(0, 0)]
154
+ assert ctx2[(1, 0)] == ctx1[(1, 0)]
155
+ assert ctx2[(2, 0)] == ctx1[(2, 0)]
156
+
157
+
158
+ @pytest.mark.parametrize(
159
+ "axis, gmap, expected",
160
+ [
161
+ (
162
+ 0,
163
+ [1, 2],
164
+ {
165
+ (0, 0): [("background-color", "#fff7fb"), ("color", "#000000")],
166
+ (1, 0): [("background-color", "#023858"), ("color", "#f1f1f1")],
167
+ (0, 1): [("background-color", "#fff7fb"), ("color", "#000000")],
168
+ (1, 1): [("background-color", "#023858"), ("color", "#f1f1f1")],
169
+ },
170
+ ),
171
+ (
172
+ 1,
173
+ [1, 2],
174
+ {
175
+ (0, 0): [("background-color", "#fff7fb"), ("color", "#000000")],
176
+ (1, 0): [("background-color", "#fff7fb"), ("color", "#000000")],
177
+ (0, 1): [("background-color", "#023858"), ("color", "#f1f1f1")],
178
+ (1, 1): [("background-color", "#023858"), ("color", "#f1f1f1")],
179
+ },
180
+ ),
181
+ (
182
+ None,
183
+ np.array([[2, 1], [1, 2]]),
184
+ {
185
+ (0, 0): [("background-color", "#023858"), ("color", "#f1f1f1")],
186
+ (1, 0): [("background-color", "#fff7fb"), ("color", "#000000")],
187
+ (0, 1): [("background-color", "#fff7fb"), ("color", "#000000")],
188
+ (1, 1): [("background-color", "#023858"), ("color", "#f1f1f1")],
189
+ },
190
+ ),
191
+ ],
192
+ )
193
+ def test_background_gradient_gmap_array(styler_blank, axis, gmap, expected):
194
+ # tests when gmap is given as a sequence and converted to ndarray
195
+ result = styler_blank.background_gradient(axis=axis, gmap=gmap)._compute().ctx
196
+ assert result == expected
197
+
198
+
199
+ @pytest.mark.parametrize(
200
+ "gmap, axis", [([1, 2, 3], 0), ([1, 2], 1), (np.array([[1, 2], [1, 2]]), None)]
201
+ )
202
+ def test_background_gradient_gmap_array_raises(gmap, axis):
203
+ # test when gmap as converted ndarray is bad shape
204
+ df = DataFrame([[0, 0, 0], [0, 0, 0]])
205
+ msg = "supplied 'gmap' is not correct shape"
206
+ with pytest.raises(ValueError, match=msg):
207
+ df.style.background_gradient(gmap=gmap, axis=axis)._compute()
208
+
209
+
210
+ @pytest.mark.parametrize(
211
+ "gmap",
212
+ [
213
+ DataFrame( # reverse the columns
214
+ [[2, 1], [1, 2]], columns=["B", "A"], index=["X", "Y"]
215
+ ),
216
+ DataFrame( # reverse the index
217
+ [[2, 1], [1, 2]], columns=["A", "B"], index=["Y", "X"]
218
+ ),
219
+ DataFrame( # reverse the index and columns
220
+ [[1, 2], [2, 1]], columns=["B", "A"], index=["Y", "X"]
221
+ ),
222
+ DataFrame( # add unnecessary columns
223
+ [[1, 2, 3], [2, 1, 3]], columns=["A", "B", "C"], index=["X", "Y"]
224
+ ),
225
+ DataFrame( # add unnecessary index
226
+ [[1, 2], [2, 1], [3, 3]], columns=["A", "B"], index=["X", "Y", "Z"]
227
+ ),
228
+ ],
229
+ )
230
+ @pytest.mark.parametrize(
231
+ "subset, exp_gmap", # exp_gmap is underlying map DataFrame should conform to
232
+ [
233
+ (None, [[1, 2], [2, 1]]),
234
+ (["A"], [[1], [2]]), # slice only column "A" in data and gmap
235
+ (["B", "A"], [[2, 1], [1, 2]]), # reverse the columns in data
236
+ (IndexSlice["X", :], [[1, 2]]), # slice only index "X" in data and gmap
237
+ (IndexSlice[["Y", "X"], :], [[2, 1], [1, 2]]), # reverse the index in data
238
+ ],
239
+ )
240
+ def test_background_gradient_gmap_dataframe_align(styler_blank, gmap, subset, exp_gmap):
241
+ # test gmap given as DataFrame that it aligns to the data including subset
242
+ expected = styler_blank.background_gradient(axis=None, gmap=exp_gmap, subset=subset)
243
+ result = styler_blank.background_gradient(axis=None, gmap=gmap, subset=subset)
244
+ assert expected._compute().ctx == result._compute().ctx
245
+
246
+
247
+ @pytest.mark.parametrize(
248
+ "gmap, axis, exp_gmap",
249
+ [
250
+ (Series([2, 1], index=["Y", "X"]), 0, [[1, 1], [2, 2]]), # revrse the index
251
+ (Series([2, 1], index=["B", "A"]), 1, [[1, 2], [1, 2]]), # revrse the cols
252
+ (Series([1, 2, 3], index=["X", "Y", "Z"]), 0, [[1, 1], [2, 2]]), # add idx
253
+ (Series([1, 2, 3], index=["A", "B", "C"]), 1, [[1, 2], [1, 2]]), # add col
254
+ ],
255
+ )
256
+ def test_background_gradient_gmap_series_align(styler_blank, gmap, axis, exp_gmap):
257
+ # test gmap given as Series that it aligns to the data including subset
258
+ expected = styler_blank.background_gradient(axis=None, gmap=exp_gmap)._compute()
259
+ result = styler_blank.background_gradient(axis=axis, gmap=gmap)._compute()
260
+ assert expected.ctx == result.ctx
261
+
262
+
263
+ @pytest.mark.parametrize(
264
+ "gmap, axis",
265
+ [
266
+ (DataFrame([[1, 2], [2, 1]], columns=["A", "B"], index=["X", "Y"]), 1),
267
+ (DataFrame([[1, 2], [2, 1]], columns=["A", "B"], index=["X", "Y"]), 0),
268
+ ],
269
+ )
270
+ def test_background_gradient_gmap_wrong_dataframe(styler_blank, gmap, axis):
271
+ # test giving a gmap in DataFrame but with wrong axis
272
+ msg = "'gmap' is a DataFrame but underlying data for operations is a Series"
273
+ with pytest.raises(ValueError, match=msg):
274
+ styler_blank.background_gradient(gmap=gmap, axis=axis)._compute()
275
+
276
+
277
+ def test_background_gradient_gmap_wrong_series(styler_blank):
278
+ # test giving a gmap in Series form but with wrong axis
279
+ msg = "'gmap' is a Series but underlying data for operations is a DataFrame"
280
+ gmap = Series([1, 2], index=["X", "Y"])
281
+ with pytest.raises(ValueError, match=msg):
282
+ styler_blank.background_gradient(gmap=gmap, axis=None)._compute()
283
+
284
+
285
+ def test_background_gradient_nullable_dtypes():
286
+ # GH 50712
287
+ df1 = DataFrame([[1], [0], [np.nan]], dtype=float)
288
+ df2 = DataFrame([[1], [0], [None]], dtype="Int64")
289
+
290
+ ctx1 = df1.style.background_gradient()._compute().ctx
291
+ ctx2 = df2.style.background_gradient()._compute().ctx
292
+ assert ctx1 == ctx2
293
+
294
+
295
+ @pytest.mark.parametrize(
296
+ "cmap",
297
+ ["PuBu", mpl.colormaps["PuBu"]],
298
+ )
299
+ def test_bar_colormap(cmap):
300
+ data = DataFrame([[1, 2], [3, 4]])
301
+ ctx = data.style.bar(cmap=cmap, axis=None)._compute().ctx
302
+ pubu_colors = {
303
+ (0, 0): "#d0d1e6",
304
+ (1, 0): "#056faf",
305
+ (0, 1): "#73a9cf",
306
+ (1, 1): "#023858",
307
+ }
308
+ for k, v in pubu_colors.items():
309
+ assert v in ctx[k][1][1]
310
+
311
+
312
+ def test_bar_color_raises(df):
313
+ msg = "`color` must be string or list or tuple of 2 strings"
314
+ with pytest.raises(ValueError, match=msg):
315
+ df.style.bar(color={"a", "b"}).to_html()
316
+ with pytest.raises(ValueError, match=msg):
317
+ df.style.bar(color=["a", "b", "c"]).to_html()
318
+
319
+ msg = "`color` and `cmap` cannot both be given"
320
+ with pytest.raises(ValueError, match=msg):
321
+ df.style.bar(color="something", cmap="something else").to_html()
322
+
323
+
324
+ @pytest.mark.parametrize(
325
+ "plot_method",
326
+ ["scatter", "hexbin"],
327
+ )
328
+ def test_pass_colormap_instance(df, plot_method):
329
+ # https://github.com/pandas-dev/pandas/issues/49374
330
+ cmap = mpl.colors.ListedColormap([[1, 1, 1], [0, 0, 0]])
331
+ df["c"] = df.A + df.B
332
+ kwargs = {"x": "A", "y": "B", "c": "c", "colormap": cmap}
333
+ if plot_method == "hexbin":
334
+ kwargs["C"] = kwargs.pop("c")
335
+ getattr(df.plot, plot_method)(**kwargs)
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/test_non_unique.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from textwrap import dedent
2
+
3
+ import pytest
4
+
5
+ from pandas import (
6
+ DataFrame,
7
+ IndexSlice,
8
+ )
9
+
10
+ pytest.importorskip("jinja2")
11
+
12
+ from pandas.io.formats.style import Styler
13
+
14
+
15
+ @pytest.fixture
16
+ def df():
17
+ return DataFrame(
18
+ [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
19
+ index=["i", "j", "j"],
20
+ columns=["c", "d", "d"],
21
+ dtype=float,
22
+ )
23
+
24
+
25
+ @pytest.fixture
26
+ def styler(df):
27
+ return Styler(df, uuid_len=0)
28
+
29
+
30
+ def test_format_non_unique(df):
31
+ # GH 41269
32
+
33
+ # test dict
34
+ html = df.style.format({"d": "{:.1f}"}).to_html()
35
+ for val in ["1.000000<", "4.000000<", "7.000000<"]:
36
+ assert val in html
37
+ for val in ["2.0<", "3.0<", "5.0<", "6.0<", "8.0<", "9.0<"]:
38
+ assert val in html
39
+
40
+ # test subset
41
+ html = df.style.format(precision=1, subset=IndexSlice["j", "d"]).to_html()
42
+ for val in ["1.000000<", "4.000000<", "7.000000<", "2.000000<", "3.000000<"]:
43
+ assert val in html
44
+ for val in ["5.0<", "6.0<", "8.0<", "9.0<"]:
45
+ assert val in html
46
+
47
+
48
+ @pytest.mark.parametrize("func", ["apply", "map"])
49
+ def test_apply_map_non_unique_raises(df, func):
50
+ # GH 41269
51
+ if func == "apply":
52
+ op = lambda s: ["color: red;"] * len(s)
53
+ else:
54
+ op = lambda v: "color: red;"
55
+
56
+ with pytest.raises(KeyError, match="`Styler.apply` and `.map` are not"):
57
+ getattr(df.style, func)(op)._compute()
58
+
59
+
60
+ def test_table_styles_dict_non_unique_index(styler):
61
+ styles = styler.set_table_styles(
62
+ {"j": [{"selector": "td", "props": "a: v;"}]}, axis=1
63
+ ).table_styles
64
+ assert styles == [
65
+ {"selector": "td.row1", "props": [("a", "v")]},
66
+ {"selector": "td.row2", "props": [("a", "v")]},
67
+ ]
68
+
69
+
70
+ def test_table_styles_dict_non_unique_columns(styler):
71
+ styles = styler.set_table_styles(
72
+ {"d": [{"selector": "td", "props": "a: v;"}]}, axis=0
73
+ ).table_styles
74
+ assert styles == [
75
+ {"selector": "td.col1", "props": [("a", "v")]},
76
+ {"selector": "td.col2", "props": [("a", "v")]},
77
+ ]
78
+
79
+
80
+ def test_tooltips_non_unique_raises(styler):
81
+ # ttips has unique keys
82
+ ttips = DataFrame([["1", "2"], ["3", "4"]], columns=["c", "d"], index=["a", "b"])
83
+ styler.set_tooltips(ttips=ttips) # OK
84
+
85
+ # ttips has non-unique columns
86
+ ttips = DataFrame([["1", "2"], ["3", "4"]], columns=["c", "c"], index=["a", "b"])
87
+ with pytest.raises(KeyError, match="Tooltips render only if `ttips` has unique"):
88
+ styler.set_tooltips(ttips=ttips)
89
+
90
+ # ttips has non-unique index
91
+ ttips = DataFrame([["1", "2"], ["3", "4"]], columns=["c", "d"], index=["a", "a"])
92
+ with pytest.raises(KeyError, match="Tooltips render only if `ttips` has unique"):
93
+ styler.set_tooltips(ttips=ttips)
94
+
95
+
96
+ def test_set_td_classes_non_unique_raises(styler):
97
+ # classes has unique keys
98
+ classes = DataFrame([["1", "2"], ["3", "4"]], columns=["c", "d"], index=["a", "b"])
99
+ styler.set_td_classes(classes=classes) # OK
100
+
101
+ # classes has non-unique columns
102
+ classes = DataFrame([["1", "2"], ["3", "4"]], columns=["c", "c"], index=["a", "b"])
103
+ with pytest.raises(KeyError, match="Classes render only if `classes` has unique"):
104
+ styler.set_td_classes(classes=classes)
105
+
106
+ # classes has non-unique index
107
+ classes = DataFrame([["1", "2"], ["3", "4"]], columns=["c", "d"], index=["a", "a"])
108
+ with pytest.raises(KeyError, match="Classes render only if `classes` has unique"):
109
+ styler.set_td_classes(classes=classes)
110
+
111
+
112
+ def test_hide_columns_non_unique(styler):
113
+ ctx = styler.hide(["d"], axis="columns")._translate(True, True)
114
+
115
+ assert ctx["head"][0][1]["display_value"] == "c"
116
+ assert ctx["head"][0][1]["is_visible"] is True
117
+
118
+ assert ctx["head"][0][2]["display_value"] == "d"
119
+ assert ctx["head"][0][2]["is_visible"] is False
120
+
121
+ assert ctx["head"][0][3]["display_value"] == "d"
122
+ assert ctx["head"][0][3]["is_visible"] is False
123
+
124
+ assert ctx["body"][0][1]["is_visible"] is True
125
+ assert ctx["body"][0][2]["is_visible"] is False
126
+ assert ctx["body"][0][3]["is_visible"] is False
127
+
128
+
129
+ def test_latex_non_unique(styler):
130
+ result = styler.to_latex()
131
+ assert result == dedent(
132
+ """\
133
+ \\begin{tabular}{lrrr}
134
+ & c & d & d \\\\
135
+ i & 1.000000 & 2.000000 & 3.000000 \\\\
136
+ j & 4.000000 & 5.000000 & 6.000000 \\\\
137
+ j & 7.000000 & 8.000000 & 9.000000 \\\\
138
+ \\end{tabular}
139
+ """
140
+ )
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/test_style.py ADDED
@@ -0,0 +1,1588 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import copy
3
+ import re
4
+ from textwrap import dedent
5
+
6
+ import numpy as np
7
+ import pytest
8
+
9
+ from pandas import (
10
+ DataFrame,
11
+ IndexSlice,
12
+ MultiIndex,
13
+ Series,
14
+ option_context,
15
+ )
16
+ import pandas._testing as tm
17
+
18
+ jinja2 = pytest.importorskip("jinja2")
19
+ from pandas.io.formats.style import ( # isort:skip
20
+ Styler,
21
+ )
22
+ from pandas.io.formats.style_render import (
23
+ _get_level_lengths,
24
+ _get_trimming_maximums,
25
+ maybe_convert_css_to_tuples,
26
+ non_reducing_slice,
27
+ )
28
+
29
+
30
+ @pytest.fixture
31
+ def mi_df():
32
+ return DataFrame(
33
+ [[1, 2], [3, 4]],
34
+ index=MultiIndex.from_product([["i0"], ["i1_a", "i1_b"]]),
35
+ columns=MultiIndex.from_product([["c0"], ["c1_a", "c1_b"]]),
36
+ dtype=int,
37
+ )
38
+
39
+
40
+ @pytest.fixture
41
+ def mi_styler(mi_df):
42
+ return Styler(mi_df, uuid_len=0)
43
+
44
+
45
+ @pytest.fixture
46
+ def mi_styler_comp(mi_styler):
47
+ # comprehensively add features to mi_styler
48
+ mi_styler = mi_styler._copy(deepcopy=True)
49
+ mi_styler.css = {**mi_styler.css, "row": "ROW", "col": "COL"}
50
+ mi_styler.uuid_len = 5
51
+ mi_styler.uuid = "abcde"
52
+ mi_styler.set_caption("capt")
53
+ mi_styler.set_table_styles([{"selector": "a", "props": "a:v;"}])
54
+ mi_styler.hide(axis="columns")
55
+ mi_styler.hide([("c0", "c1_a")], axis="columns", names=True)
56
+ mi_styler.hide(axis="index")
57
+ mi_styler.hide([("i0", "i1_a")], axis="index", names=True)
58
+ mi_styler.set_table_attributes('class="box"')
59
+ other = mi_styler.data.agg(["mean"])
60
+ other.index = MultiIndex.from_product([[""], other.index])
61
+ mi_styler.concat(other.style)
62
+ mi_styler.format(na_rep="MISSING", precision=3)
63
+ mi_styler.format_index(precision=2, axis=0)
64
+ mi_styler.format_index(precision=4, axis=1)
65
+ mi_styler.highlight_max(axis=None)
66
+ mi_styler.map_index(lambda x: "color: white;", axis=0)
67
+ mi_styler.map_index(lambda x: "color: black;", axis=1)
68
+ mi_styler.set_td_classes(
69
+ DataFrame(
70
+ [["a", "b"], ["a", "c"]], index=mi_styler.index, columns=mi_styler.columns
71
+ )
72
+ )
73
+ mi_styler.set_tooltips(
74
+ DataFrame(
75
+ [["a2", "b2"], ["a2", "c2"]],
76
+ index=mi_styler.index,
77
+ columns=mi_styler.columns,
78
+ )
79
+ )
80
+ return mi_styler
81
+
82
+
83
+ @pytest.fixture
84
+ def blank_value():
85
+ return "&nbsp;"
86
+
87
+
88
+ @pytest.fixture
89
+ def df():
90
+ df = DataFrame({"A": [0, 1], "B": np.random.default_rng(2).standard_normal(2)})
91
+ return df
92
+
93
+
94
+ @pytest.fixture
95
+ def styler(df):
96
+ df = DataFrame({"A": [0, 1], "B": np.random.default_rng(2).standard_normal(2)})
97
+ return Styler(df)
98
+
99
+
100
+ @pytest.mark.parametrize(
101
+ "sparse_columns, exp_cols",
102
+ [
103
+ (
104
+ True,
105
+ [
106
+ {"is_visible": True, "attributes": 'colspan="2"', "value": "c0"},
107
+ {"is_visible": False, "attributes": "", "value": "c0"},
108
+ ],
109
+ ),
110
+ (
111
+ False,
112
+ [
113
+ {"is_visible": True, "attributes": "", "value": "c0"},
114
+ {"is_visible": True, "attributes": "", "value": "c0"},
115
+ ],
116
+ ),
117
+ ],
118
+ )
119
+ def test_mi_styler_sparsify_columns(mi_styler, sparse_columns, exp_cols):
120
+ exp_l1_c0 = {"is_visible": True, "attributes": "", "display_value": "c1_a"}
121
+ exp_l1_c1 = {"is_visible": True, "attributes": "", "display_value": "c1_b"}
122
+
123
+ ctx = mi_styler._translate(True, sparse_columns)
124
+
125
+ assert exp_cols[0].items() <= ctx["head"][0][2].items()
126
+ assert exp_cols[1].items() <= ctx["head"][0][3].items()
127
+ assert exp_l1_c0.items() <= ctx["head"][1][2].items()
128
+ assert exp_l1_c1.items() <= ctx["head"][1][3].items()
129
+
130
+
131
+ @pytest.mark.parametrize(
132
+ "sparse_index, exp_rows",
133
+ [
134
+ (
135
+ True,
136
+ [
137
+ {"is_visible": True, "attributes": 'rowspan="2"', "value": "i0"},
138
+ {"is_visible": False, "attributes": "", "value": "i0"},
139
+ ],
140
+ ),
141
+ (
142
+ False,
143
+ [
144
+ {"is_visible": True, "attributes": "", "value": "i0"},
145
+ {"is_visible": True, "attributes": "", "value": "i0"},
146
+ ],
147
+ ),
148
+ ],
149
+ )
150
+ def test_mi_styler_sparsify_index(mi_styler, sparse_index, exp_rows):
151
+ exp_l1_r0 = {"is_visible": True, "attributes": "", "display_value": "i1_a"}
152
+ exp_l1_r1 = {"is_visible": True, "attributes": "", "display_value": "i1_b"}
153
+
154
+ ctx = mi_styler._translate(sparse_index, True)
155
+
156
+ assert exp_rows[0].items() <= ctx["body"][0][0].items()
157
+ assert exp_rows[1].items() <= ctx["body"][1][0].items()
158
+ assert exp_l1_r0.items() <= ctx["body"][0][1].items()
159
+ assert exp_l1_r1.items() <= ctx["body"][1][1].items()
160
+
161
+
162
+ def test_mi_styler_sparsify_options(mi_styler):
163
+ with option_context("styler.sparse.index", False):
164
+ html1 = mi_styler.to_html()
165
+ with option_context("styler.sparse.index", True):
166
+ html2 = mi_styler.to_html()
167
+
168
+ assert html1 != html2
169
+
170
+ with option_context("styler.sparse.columns", False):
171
+ html1 = mi_styler.to_html()
172
+ with option_context("styler.sparse.columns", True):
173
+ html2 = mi_styler.to_html()
174
+
175
+ assert html1 != html2
176
+
177
+
178
+ @pytest.mark.parametrize(
179
+ "rn, cn, max_els, max_rows, max_cols, exp_rn, exp_cn",
180
+ [
181
+ (100, 100, 100, None, None, 12, 6), # reduce to (12, 6) < 100 elements
182
+ (1000, 3, 750, None, None, 250, 3), # dynamically reduce rows to 250, keep cols
183
+ (4, 1000, 500, None, None, 4, 125), # dynamically reduce cols to 125, keep rows
184
+ (1000, 3, 750, 10, None, 10, 3), # overwrite above dynamics with max_row
185
+ (4, 1000, 500, None, 5, 4, 5), # overwrite above dynamics with max_col
186
+ (100, 100, 700, 50, 50, 25, 25), # rows cols below given maxes so < 700 elmts
187
+ ],
188
+ )
189
+ def test_trimming_maximum(rn, cn, max_els, max_rows, max_cols, exp_rn, exp_cn):
190
+ rn, cn = _get_trimming_maximums(
191
+ rn, cn, max_els, max_rows, max_cols, scaling_factor=0.5
192
+ )
193
+ assert (rn, cn) == (exp_rn, exp_cn)
194
+
195
+
196
+ @pytest.mark.parametrize(
197
+ "option, val",
198
+ [
199
+ ("styler.render.max_elements", 6),
200
+ ("styler.render.max_rows", 3),
201
+ ],
202
+ )
203
+ def test_render_trimming_rows(option, val):
204
+ # test auto and specific trimming of rows
205
+ df = DataFrame(np.arange(120).reshape(60, 2))
206
+ with option_context(option, val):
207
+ ctx = df.style._translate(True, True)
208
+ assert len(ctx["head"][0]) == 3 # index + 2 data cols
209
+ assert len(ctx["body"]) == 4 # 3 data rows + trimming row
210
+ assert len(ctx["body"][0]) == 3 # index + 2 data cols
211
+
212
+
213
+ @pytest.mark.parametrize(
214
+ "option, val",
215
+ [
216
+ ("styler.render.max_elements", 6),
217
+ ("styler.render.max_columns", 2),
218
+ ],
219
+ )
220
+ def test_render_trimming_cols(option, val):
221
+ # test auto and specific trimming of cols
222
+ df = DataFrame(np.arange(30).reshape(3, 10))
223
+ with option_context(option, val):
224
+ ctx = df.style._translate(True, True)
225
+ assert len(ctx["head"][0]) == 4 # index + 2 data cols + trimming col
226
+ assert len(ctx["body"]) == 3 # 3 data rows
227
+ assert len(ctx["body"][0]) == 4 # index + 2 data cols + trimming col
228
+
229
+
230
+ def test_render_trimming_mi():
231
+ midx = MultiIndex.from_product([[1, 2], [1, 2, 3]])
232
+ df = DataFrame(np.arange(36).reshape(6, 6), columns=midx, index=midx)
233
+ with option_context("styler.render.max_elements", 4):
234
+ ctx = df.style._translate(True, True)
235
+
236
+ assert len(ctx["body"][0]) == 5 # 2 indexes + 2 data cols + trimming row
237
+ assert {"attributes": 'rowspan="2"'}.items() <= ctx["body"][0][0].items()
238
+ assert {"class": "data row0 col_trim"}.items() <= ctx["body"][0][4].items()
239
+ assert {"class": "data row_trim col_trim"}.items() <= ctx["body"][2][4].items()
240
+ assert len(ctx["body"]) == 3 # 2 data rows + trimming row
241
+
242
+
243
+ def test_render_empty_mi():
244
+ # GH 43305
245
+ df = DataFrame(index=MultiIndex.from_product([["A"], [0, 1]], names=[None, "one"]))
246
+ expected = dedent(
247
+ """\
248
+ >
249
+ <thead>
250
+ <tr>
251
+ <th class="index_name level0" >&nbsp;</th>
252
+ <th class="index_name level1" >one</th>
253
+ </tr>
254
+ </thead>
255
+ """
256
+ )
257
+ assert expected in df.style.to_html()
258
+
259
+
260
+ @pytest.mark.parametrize("comprehensive", [True, False])
261
+ @pytest.mark.parametrize("render", [True, False])
262
+ @pytest.mark.parametrize("deepcopy", [True, False])
263
+ def test_copy(comprehensive, render, deepcopy, mi_styler, mi_styler_comp):
264
+ styler = mi_styler_comp if comprehensive else mi_styler
265
+ styler.uuid_len = 5
266
+
267
+ s2 = copy.deepcopy(styler) if deepcopy else copy.copy(styler) # make copy and check
268
+ assert s2 is not styler
269
+
270
+ if render:
271
+ styler.to_html()
272
+
273
+ excl = [
274
+ "cellstyle_map", # render time vars..
275
+ "cellstyle_map_columns",
276
+ "cellstyle_map_index",
277
+ "template_latex", # render templates are class level
278
+ "template_html",
279
+ "template_html_style",
280
+ "template_html_table",
281
+ ]
282
+ if not deepcopy: # check memory locations are equal for all included attributes
283
+ for attr in [a for a in styler.__dict__ if (not callable(a) and a not in excl)]:
284
+ assert id(getattr(s2, attr)) == id(getattr(styler, attr))
285
+ else: # check memory locations are different for nested or mutable vars
286
+ shallow = [
287
+ "data",
288
+ "columns",
289
+ "index",
290
+ "uuid_len",
291
+ "uuid",
292
+ "caption",
293
+ "cell_ids",
294
+ "hide_index_",
295
+ "hide_columns_",
296
+ "hide_index_names",
297
+ "hide_column_names",
298
+ "table_attributes",
299
+ ]
300
+ for attr in shallow:
301
+ assert id(getattr(s2, attr)) == id(getattr(styler, attr))
302
+
303
+ for attr in [
304
+ a
305
+ for a in styler.__dict__
306
+ if (not callable(a) and a not in excl and a not in shallow)
307
+ ]:
308
+ if getattr(s2, attr) is None:
309
+ assert id(getattr(s2, attr)) == id(getattr(styler, attr))
310
+ else:
311
+ assert id(getattr(s2, attr)) != id(getattr(styler, attr))
312
+
313
+
314
+ @pytest.mark.parametrize("deepcopy", [True, False])
315
+ def test_inherited_copy(mi_styler, deepcopy):
316
+ # Ensure that the inherited class is preserved when a Styler object is copied.
317
+ # GH 52728
318
+ class CustomStyler(Styler):
319
+ pass
320
+
321
+ custom_styler = CustomStyler(mi_styler.data)
322
+ custom_styler_copy = (
323
+ copy.deepcopy(custom_styler) if deepcopy else copy.copy(custom_styler)
324
+ )
325
+ assert isinstance(custom_styler_copy, CustomStyler)
326
+
327
+
328
+ def test_clear(mi_styler_comp):
329
+ # NOTE: if this test fails for new features then 'mi_styler_comp' should be updated
330
+ # to ensure proper testing of the 'copy', 'clear', 'export' methods with new feature
331
+ # GH 40675
332
+ styler = mi_styler_comp
333
+ styler._compute() # execute applied methods
334
+
335
+ clean_copy = Styler(styler.data, uuid=styler.uuid)
336
+
337
+ excl = [
338
+ "data",
339
+ "index",
340
+ "columns",
341
+ "uuid",
342
+ "uuid_len", # uuid is set to be the same on styler and clean_copy
343
+ "cell_ids",
344
+ "cellstyle_map", # execution time only
345
+ "cellstyle_map_columns", # execution time only
346
+ "cellstyle_map_index", # execution time only
347
+ "template_latex", # render templates are class level
348
+ "template_html",
349
+ "template_html_style",
350
+ "template_html_table",
351
+ ]
352
+ # tests vars are not same vals on obj and clean copy before clear (except for excl)
353
+ for attr in [a for a in styler.__dict__ if not (callable(a) or a in excl)]:
354
+ res = getattr(styler, attr) == getattr(clean_copy, attr)
355
+ if hasattr(res, "__iter__") and len(res) > 0:
356
+ assert not all(res) # some element in iterable differs
357
+ elif hasattr(res, "__iter__") and len(res) == 0:
358
+ pass # empty array
359
+ else:
360
+ assert not res # explicit var differs
361
+
362
+ # test vars have same vales on obj and clean copy after clearing
363
+ styler.clear()
364
+ for attr in [a for a in styler.__dict__ if not callable(a)]:
365
+ res = getattr(styler, attr) == getattr(clean_copy, attr)
366
+ assert all(res) if hasattr(res, "__iter__") else res
367
+
368
+
369
+ def test_export(mi_styler_comp, mi_styler):
370
+ exp_attrs = [
371
+ "_todo",
372
+ "hide_index_",
373
+ "hide_index_names",
374
+ "hide_columns_",
375
+ "hide_column_names",
376
+ "table_attributes",
377
+ "table_styles",
378
+ "css",
379
+ ]
380
+ for attr in exp_attrs:
381
+ check = getattr(mi_styler, attr) == getattr(mi_styler_comp, attr)
382
+ assert not (
383
+ all(check) if (hasattr(check, "__iter__") and len(check) > 0) else check
384
+ )
385
+
386
+ export = mi_styler_comp.export()
387
+ used = mi_styler.use(export)
388
+ for attr in exp_attrs:
389
+ check = getattr(used, attr) == getattr(mi_styler_comp, attr)
390
+ assert all(check) if (hasattr(check, "__iter__") and len(check) > 0) else check
391
+
392
+ used.to_html()
393
+
394
+
395
+ def test_hide_raises(mi_styler):
396
+ msg = "`subset` and `level` cannot be passed simultaneously"
397
+ with pytest.raises(ValueError, match=msg):
398
+ mi_styler.hide(axis="index", subset="something", level="something else")
399
+
400
+ msg = "`level` must be of type `int`, `str` or list of such"
401
+ with pytest.raises(ValueError, match=msg):
402
+ mi_styler.hide(axis="index", level={"bad": 1, "type": 2})
403
+
404
+
405
+ @pytest.mark.parametrize("level", [1, "one", [1], ["one"]])
406
+ def test_hide_index_level(mi_styler, level):
407
+ mi_styler.index.names, mi_styler.columns.names = ["zero", "one"], ["zero", "one"]
408
+ ctx = mi_styler.hide(axis="index", level=level)._translate(False, True)
409
+ assert len(ctx["head"][0]) == 3
410
+ assert len(ctx["head"][1]) == 3
411
+ assert len(ctx["head"][2]) == 4
412
+ assert ctx["head"][2][0]["is_visible"]
413
+ assert not ctx["head"][2][1]["is_visible"]
414
+
415
+ assert ctx["body"][0][0]["is_visible"]
416
+ assert not ctx["body"][0][1]["is_visible"]
417
+ assert ctx["body"][1][0]["is_visible"]
418
+ assert not ctx["body"][1][1]["is_visible"]
419
+
420
+
421
+ @pytest.mark.parametrize("level", [1, "one", [1], ["one"]])
422
+ @pytest.mark.parametrize("names", [True, False])
423
+ def test_hide_columns_level(mi_styler, level, names):
424
+ mi_styler.columns.names = ["zero", "one"]
425
+ if names:
426
+ mi_styler.index.names = ["zero", "one"]
427
+ ctx = mi_styler.hide(axis="columns", level=level)._translate(True, False)
428
+ assert len(ctx["head"]) == (2 if names else 1)
429
+
430
+
431
+ @pytest.mark.parametrize("method", ["map", "apply"])
432
+ @pytest.mark.parametrize("axis", ["index", "columns"])
433
+ def test_apply_map_header(method, axis):
434
+ # GH 41893
435
+ df = DataFrame({"A": [0, 0], "B": [1, 1]}, index=["C", "D"])
436
+ func = {
437
+ "apply": lambda s: ["attr: val" if ("A" in v or "C" in v) else "" for v in s],
438
+ "map": lambda v: "attr: val" if ("A" in v or "C" in v) else "",
439
+ }
440
+
441
+ # test execution added to todo
442
+ result = getattr(df.style, f"{method}_index")(func[method], axis=axis)
443
+ assert len(result._todo) == 1
444
+ assert len(getattr(result, f"ctx_{axis}")) == 0
445
+
446
+ # test ctx object on compute
447
+ result._compute()
448
+ expected = {
449
+ (0, 0): [("attr", "val")],
450
+ }
451
+ assert getattr(result, f"ctx_{axis}") == expected
452
+
453
+
454
+ @pytest.mark.parametrize("method", ["apply", "map"])
455
+ @pytest.mark.parametrize("axis", ["index", "columns"])
456
+ def test_apply_map_header_mi(mi_styler, method, axis):
457
+ # GH 41893
458
+ func = {
459
+ "apply": lambda s: ["attr: val;" if "b" in v else "" for v in s],
460
+ "map": lambda v: "attr: val" if "b" in v else "",
461
+ }
462
+ result = getattr(mi_styler, f"{method}_index")(func[method], axis=axis)._compute()
463
+ expected = {(1, 1): [("attr", "val")]}
464
+ assert getattr(result, f"ctx_{axis}") == expected
465
+
466
+
467
+ def test_apply_map_header_raises(mi_styler):
468
+ # GH 41893
469
+ with pytest.raises(ValueError, match="No axis named bad for object type DataFrame"):
470
+ mi_styler.map_index(lambda v: "attr: val;", axis="bad")._compute()
471
+
472
+
473
+ class TestStyler:
474
+ def test_init_non_pandas(self):
475
+ msg = "``data`` must be a Series or DataFrame"
476
+ with pytest.raises(TypeError, match=msg):
477
+ Styler([1, 2, 3])
478
+
479
+ def test_init_series(self):
480
+ result = Styler(Series([1, 2]))
481
+ assert result.data.ndim == 2
482
+
483
+ def test_repr_html_ok(self, styler):
484
+ styler._repr_html_()
485
+
486
+ def test_repr_html_mathjax(self, styler):
487
+ # gh-19824 / 41395
488
+ assert "tex2jax_ignore" not in styler._repr_html_()
489
+
490
+ with option_context("styler.html.mathjax", False):
491
+ assert "tex2jax_ignore" in styler._repr_html_()
492
+
493
+ def test_update_ctx(self, styler):
494
+ styler._update_ctx(DataFrame({"A": ["color: red", "color: blue"]}))
495
+ expected = {(0, 0): [("color", "red")], (1, 0): [("color", "blue")]}
496
+ assert styler.ctx == expected
497
+
498
+ def test_update_ctx_flatten_multi_and_trailing_semi(self, styler):
499
+ attrs = DataFrame({"A": ["color: red; foo: bar", "color:blue ; foo: baz;"]})
500
+ styler._update_ctx(attrs)
501
+ expected = {
502
+ (0, 0): [("color", "red"), ("foo", "bar")],
503
+ (1, 0): [("color", "blue"), ("foo", "baz")],
504
+ }
505
+ assert styler.ctx == expected
506
+
507
+ def test_render(self):
508
+ df = DataFrame({"A": [0, 1]})
509
+ style = lambda x: Series(["color: red", "color: blue"], name=x.name)
510
+ s = Styler(df, uuid="AB").apply(style)
511
+ s.to_html()
512
+ # it worked?
513
+
514
+ def test_multiple_render(self, df):
515
+ # GH 39396
516
+ s = Styler(df, uuid_len=0).map(lambda x: "color: red;", subset=["A"])
517
+ s.to_html() # do 2 renders to ensure css styles not duplicated
518
+ assert (
519
+ '<style type="text/css">\n#T__row0_col0, #T__row1_col0 {\n'
520
+ " color: red;\n}\n</style>" in s.to_html()
521
+ )
522
+
523
+ def test_render_empty_dfs(self):
524
+ empty_df = DataFrame()
525
+ es = Styler(empty_df)
526
+ es.to_html()
527
+ # An index but no columns
528
+ DataFrame(columns=["a"]).style.to_html()
529
+ # A column but no index
530
+ DataFrame(index=["a"]).style.to_html()
531
+ # No IndexError raised?
532
+
533
+ def test_render_double(self):
534
+ df = DataFrame({"A": [0, 1]})
535
+ style = lambda x: Series(
536
+ ["color: red; border: 1px", "color: blue; border: 2px"], name=x.name
537
+ )
538
+ s = Styler(df, uuid="AB").apply(style)
539
+ s.to_html()
540
+ # it worked?
541
+
542
+ def test_set_properties(self):
543
+ df = DataFrame({"A": [0, 1]})
544
+ result = df.style.set_properties(color="white", size="10px")._compute().ctx
545
+ # order is deterministic
546
+ v = [("color", "white"), ("size", "10px")]
547
+ expected = {(0, 0): v, (1, 0): v}
548
+ assert result.keys() == expected.keys()
549
+ for v1, v2 in zip(result.values(), expected.values()):
550
+ assert sorted(v1) == sorted(v2)
551
+
552
+ def test_set_properties_subset(self):
553
+ df = DataFrame({"A": [0, 1]})
554
+ result = (
555
+ df.style.set_properties(subset=IndexSlice[0, "A"], color="white")
556
+ ._compute()
557
+ .ctx
558
+ )
559
+ expected = {(0, 0): [("color", "white")]}
560
+ assert result == expected
561
+
562
+ def test_empty_index_name_doesnt_display(self, blank_value):
563
+ # https://github.com/pandas-dev/pandas/pull/12090#issuecomment-180695902
564
+ df = DataFrame({"A": [1, 2], "B": [3, 4], "C": [5, 6]})
565
+ result = df.style._translate(True, True)
566
+ assert len(result["head"]) == 1
567
+ expected = {
568
+ "class": "blank level0",
569
+ "type": "th",
570
+ "value": blank_value,
571
+ "is_visible": True,
572
+ "display_value": blank_value,
573
+ }
574
+ assert expected.items() <= result["head"][0][0].items()
575
+
576
+ def test_index_name(self):
577
+ # https://github.com/pandas-dev/pandas/issues/11655
578
+ df = DataFrame({"A": [1, 2], "B": [3, 4], "C": [5, 6]})
579
+ result = df.set_index("A").style._translate(True, True)
580
+ expected = {
581
+ "class": "index_name level0",
582
+ "type": "th",
583
+ "value": "A",
584
+ "is_visible": True,
585
+ "display_value": "A",
586
+ }
587
+ assert expected.items() <= result["head"][1][0].items()
588
+
589
+ def test_numeric_columns(self):
590
+ # https://github.com/pandas-dev/pandas/issues/12125
591
+ # smoke test for _translate
592
+ df = DataFrame({0: [1, 2, 3]})
593
+ df.style._translate(True, True)
594
+
595
+ def test_apply_axis(self):
596
+ df = DataFrame({"A": [0, 0], "B": [1, 1]})
597
+ f = lambda x: [f"val: {x.max()}" for v in x]
598
+ result = df.style.apply(f, axis=1)
599
+ assert len(result._todo) == 1
600
+ assert len(result.ctx) == 0
601
+ result._compute()
602
+ expected = {
603
+ (0, 0): [("val", "1")],
604
+ (0, 1): [("val", "1")],
605
+ (1, 0): [("val", "1")],
606
+ (1, 1): [("val", "1")],
607
+ }
608
+ assert result.ctx == expected
609
+
610
+ result = df.style.apply(f, axis=0)
611
+ expected = {
612
+ (0, 0): [("val", "0")],
613
+ (0, 1): [("val", "1")],
614
+ (1, 0): [("val", "0")],
615
+ (1, 1): [("val", "1")],
616
+ }
617
+ result._compute()
618
+ assert result.ctx == expected
619
+ result = df.style.apply(f) # default
620
+ result._compute()
621
+ assert result.ctx == expected
622
+
623
+ @pytest.mark.parametrize("axis", [0, 1])
624
+ def test_apply_series_return(self, axis):
625
+ # GH 42014
626
+ df = DataFrame([[1, 2], [3, 4]], index=["X", "Y"], columns=["X", "Y"])
627
+
628
+ # test Series return where len(Series) < df.index or df.columns but labels OK
629
+ func = lambda s: Series(["color: red;"], index=["Y"])
630
+ result = df.style.apply(func, axis=axis)._compute().ctx
631
+ assert result[(1, 1)] == [("color", "red")]
632
+ assert result[(1 - axis, axis)] == [("color", "red")]
633
+
634
+ # test Series return where labels align but different order
635
+ func = lambda s: Series(["color: red;", "color: blue;"], index=["Y", "X"])
636
+ result = df.style.apply(func, axis=axis)._compute().ctx
637
+ assert result[(0, 0)] == [("color", "blue")]
638
+ assert result[(1, 1)] == [("color", "red")]
639
+ assert result[(1 - axis, axis)] == [("color", "red")]
640
+ assert result[(axis, 1 - axis)] == [("color", "blue")]
641
+
642
+ @pytest.mark.parametrize("index", [False, True])
643
+ @pytest.mark.parametrize("columns", [False, True])
644
+ def test_apply_dataframe_return(self, index, columns):
645
+ # GH 42014
646
+ df = DataFrame([[1, 2], [3, 4]], index=["X", "Y"], columns=["X", "Y"])
647
+ idxs = ["X", "Y"] if index else ["Y"]
648
+ cols = ["X", "Y"] if columns else ["Y"]
649
+ df_styles = DataFrame("color: red;", index=idxs, columns=cols)
650
+ result = df.style.apply(lambda x: df_styles, axis=None)._compute().ctx
651
+
652
+ assert result[(1, 1)] == [("color", "red")] # (Y,Y) styles always present
653
+ assert (result[(0, 1)] == [("color", "red")]) is index # (X,Y) only if index
654
+ assert (result[(1, 0)] == [("color", "red")]) is columns # (Y,X) only if cols
655
+ assert (result[(0, 0)] == [("color", "red")]) is (index and columns) # (X,X)
656
+
657
+ @pytest.mark.parametrize(
658
+ "slice_",
659
+ [
660
+ IndexSlice[:],
661
+ IndexSlice[:, ["A"]],
662
+ IndexSlice[[1], :],
663
+ IndexSlice[[1], ["A"]],
664
+ IndexSlice[:2, ["A", "B"]],
665
+ ],
666
+ )
667
+ @pytest.mark.parametrize("axis", [0, 1])
668
+ def test_apply_subset(self, slice_, axis, df):
669
+ def h(x, color="bar"):
670
+ return Series(f"color: {color}", index=x.index, name=x.name)
671
+
672
+ result = df.style.apply(h, axis=axis, subset=slice_, color="baz")._compute().ctx
673
+ expected = {
674
+ (r, c): [("color", "baz")]
675
+ for r, row in enumerate(df.index)
676
+ for c, col in enumerate(df.columns)
677
+ if row in df.loc[slice_].index and col in df.loc[slice_].columns
678
+ }
679
+ assert result == expected
680
+
681
+ @pytest.mark.parametrize(
682
+ "slice_",
683
+ [
684
+ IndexSlice[:],
685
+ IndexSlice[:, ["A"]],
686
+ IndexSlice[[1], :],
687
+ IndexSlice[[1], ["A"]],
688
+ IndexSlice[:2, ["A", "B"]],
689
+ ],
690
+ )
691
+ def test_map_subset(self, slice_, df):
692
+ result = df.style.map(lambda x: "color:baz;", subset=slice_)._compute().ctx
693
+ expected = {
694
+ (r, c): [("color", "baz")]
695
+ for r, row in enumerate(df.index)
696
+ for c, col in enumerate(df.columns)
697
+ if row in df.loc[slice_].index and col in df.loc[slice_].columns
698
+ }
699
+ assert result == expected
700
+
701
+ @pytest.mark.parametrize(
702
+ "slice_",
703
+ [
704
+ IndexSlice[:, IndexSlice["x", "A"]],
705
+ IndexSlice[:, IndexSlice[:, "A"]],
706
+ IndexSlice[:, IndexSlice[:, ["A", "C"]]], # missing col element
707
+ IndexSlice[IndexSlice["a", 1], :],
708
+ IndexSlice[IndexSlice[:, 1], :],
709
+ IndexSlice[IndexSlice[:, [1, 3]], :], # missing row element
710
+ IndexSlice[:, ("x", "A")],
711
+ IndexSlice[("a", 1), :],
712
+ ],
713
+ )
714
+ def test_map_subset_multiindex(self, slice_):
715
+ # GH 19861
716
+ # edited for GH 33562
717
+ if (
718
+ isinstance(slice_[-1], tuple)
719
+ and isinstance(slice_[-1][-1], list)
720
+ and "C" in slice_[-1][-1]
721
+ ):
722
+ ctx = pytest.raises(KeyError, match="C")
723
+ elif (
724
+ isinstance(slice_[0], tuple)
725
+ and isinstance(slice_[0][1], list)
726
+ and 3 in slice_[0][1]
727
+ ):
728
+ ctx = pytest.raises(KeyError, match="3")
729
+ else:
730
+ ctx = contextlib.nullcontext()
731
+
732
+ idx = MultiIndex.from_product([["a", "b"], [1, 2]])
733
+ col = MultiIndex.from_product([["x", "y"], ["A", "B"]])
734
+ df = DataFrame(np.random.default_rng(2).random((4, 4)), columns=col, index=idx)
735
+
736
+ with ctx:
737
+ df.style.map(lambda x: "color: red;", subset=slice_).to_html()
738
+
739
+ def test_map_subset_multiindex_code(self):
740
+ # https://github.com/pandas-dev/pandas/issues/25858
741
+ # Checks styler.map works with multindex when codes are provided
742
+ codes = np.array([[0, 0, 1, 1], [0, 1, 0, 1]])
743
+ columns = MultiIndex(
744
+ levels=[["a", "b"], ["%", "#"]], codes=codes, names=["", ""]
745
+ )
746
+ df = DataFrame(
747
+ [[1, -1, 1, 1], [-1, 1, 1, 1]], index=["hello", "world"], columns=columns
748
+ )
749
+ pct_subset = IndexSlice[:, IndexSlice[:, "%":"%"]]
750
+
751
+ def color_negative_red(val):
752
+ color = "red" if val < 0 else "black"
753
+ return f"color: {color}"
754
+
755
+ df.loc[pct_subset]
756
+ df.style.map(color_negative_red, subset=pct_subset)
757
+
758
+ @pytest.mark.parametrize(
759
+ "stylefunc", ["background_gradient", "bar", "text_gradient"]
760
+ )
761
+ def test_subset_for_boolean_cols(self, stylefunc):
762
+ # GH47838
763
+ df = DataFrame(
764
+ [
765
+ [1, 2],
766
+ [3, 4],
767
+ ],
768
+ columns=[False, True],
769
+ )
770
+ styled = getattr(df.style, stylefunc)()
771
+ styled._compute()
772
+ assert set(styled.ctx) == {(0, 0), (0, 1), (1, 0), (1, 1)}
773
+
774
+ def test_empty(self):
775
+ df = DataFrame({"A": [1, 0]})
776
+ s = df.style
777
+ s.ctx = {(0, 0): [("color", "red")], (1, 0): [("", "")]}
778
+
779
+ result = s._translate(True, True)["cellstyle"]
780
+ expected = [
781
+ {"props": [("color", "red")], "selectors": ["row0_col0"]},
782
+ {"props": [("", "")], "selectors": ["row1_col0"]},
783
+ ]
784
+ assert result == expected
785
+
786
+ def test_duplicate(self):
787
+ df = DataFrame({"A": [1, 0]})
788
+ s = df.style
789
+ s.ctx = {(0, 0): [("color", "red")], (1, 0): [("color", "red")]}
790
+
791
+ result = s._translate(True, True)["cellstyle"]
792
+ expected = [
793
+ {"props": [("color", "red")], "selectors": ["row0_col0", "row1_col0"]}
794
+ ]
795
+ assert result == expected
796
+
797
+ def test_init_with_na_rep(self):
798
+ # GH 21527 28358
799
+ df = DataFrame([[None, None], [1.1, 1.2]], columns=["A", "B"])
800
+
801
+ ctx = Styler(df, na_rep="NA")._translate(True, True)
802
+ assert ctx["body"][0][1]["display_value"] == "NA"
803
+ assert ctx["body"][0][2]["display_value"] == "NA"
804
+
805
+ def test_caption(self, df):
806
+ styler = Styler(df, caption="foo")
807
+ result = styler.to_html()
808
+ assert all(["caption" in result, "foo" in result])
809
+
810
+ styler = df.style
811
+ result = styler.set_caption("baz")
812
+ assert styler is result
813
+ assert styler.caption == "baz"
814
+
815
+ def test_uuid(self, df):
816
+ styler = Styler(df, uuid="abc123")
817
+ result = styler.to_html()
818
+ assert "abc123" in result
819
+
820
+ styler = df.style
821
+ result = styler.set_uuid("aaa")
822
+ assert result is styler
823
+ assert result.uuid == "aaa"
824
+
825
+ def test_unique_id(self):
826
+ # See https://github.com/pandas-dev/pandas/issues/16780
827
+ df = DataFrame({"a": [1, 3, 5, 6], "b": [2, 4, 12, 21]})
828
+ result = df.style.to_html(uuid="test")
829
+ assert "test" in result
830
+ ids = re.findall('id="(.*?)"', result)
831
+ assert np.unique(ids).size == len(ids)
832
+
833
+ def test_table_styles(self, df):
834
+ style = [{"selector": "th", "props": [("foo", "bar")]}] # default format
835
+ styler = Styler(df, table_styles=style)
836
+ result = " ".join(styler.to_html().split())
837
+ assert "th { foo: bar; }" in result
838
+
839
+ styler = df.style
840
+ result = styler.set_table_styles(style)
841
+ assert styler is result
842
+ assert styler.table_styles == style
843
+
844
+ # GH 39563
845
+ style = [{"selector": "th", "props": "foo:bar;"}] # css string format
846
+ styler = df.style.set_table_styles(style)
847
+ result = " ".join(styler.to_html().split())
848
+ assert "th { foo: bar; }" in result
849
+
850
+ def test_table_styles_multiple(self, df):
851
+ ctx = df.style.set_table_styles(
852
+ [
853
+ {"selector": "th,td", "props": "color:red;"},
854
+ {"selector": "tr", "props": "color:green;"},
855
+ ]
856
+ )._translate(True, True)["table_styles"]
857
+ assert ctx == [
858
+ {"selector": "th", "props": [("color", "red")]},
859
+ {"selector": "td", "props": [("color", "red")]},
860
+ {"selector": "tr", "props": [("color", "green")]},
861
+ ]
862
+
863
+ def test_table_styles_dict_multiple_selectors(self, df):
864
+ # GH 44011
865
+ result = df.style.set_table_styles(
866
+ {
867
+ "B": [
868
+ {"selector": "th,td", "props": [("border-left", "2px solid black")]}
869
+ ]
870
+ }
871
+ )._translate(True, True)["table_styles"]
872
+
873
+ expected = [
874
+ {"selector": "th.col1", "props": [("border-left", "2px solid black")]},
875
+ {"selector": "td.col1", "props": [("border-left", "2px solid black")]},
876
+ ]
877
+
878
+ assert result == expected
879
+
880
+ def test_maybe_convert_css_to_tuples(self):
881
+ expected = [("a", "b"), ("c", "d e")]
882
+ assert maybe_convert_css_to_tuples("a:b;c:d e;") == expected
883
+ assert maybe_convert_css_to_tuples("a: b ;c: d e ") == expected
884
+ expected = []
885
+ assert maybe_convert_css_to_tuples("") == expected
886
+
887
+ def test_maybe_convert_css_to_tuples_err(self):
888
+ msg = "Styles supplied as string must follow CSS rule formats"
889
+ with pytest.raises(ValueError, match=msg):
890
+ maybe_convert_css_to_tuples("err")
891
+
892
+ def test_table_attributes(self, df):
893
+ attributes = 'class="foo" data-bar'
894
+ styler = Styler(df, table_attributes=attributes)
895
+ result = styler.to_html()
896
+ assert 'class="foo" data-bar' in result
897
+
898
+ result = df.style.set_table_attributes(attributes).to_html()
899
+ assert 'class="foo" data-bar' in result
900
+
901
+ def test_apply_none(self):
902
+ def f(x):
903
+ return DataFrame(
904
+ np.where(x == x.max(), "color: red", ""),
905
+ index=x.index,
906
+ columns=x.columns,
907
+ )
908
+
909
+ result = DataFrame([[1, 2], [3, 4]]).style.apply(f, axis=None)._compute().ctx
910
+ assert result[(1, 1)] == [("color", "red")]
911
+
912
+ def test_trim(self, df):
913
+ result = df.style.to_html() # trim=True
914
+ assert result.count("#") == 0
915
+
916
+ result = df.style.highlight_max().to_html()
917
+ assert result.count("#") == len(df.columns)
918
+
919
+ def test_export(self, df, styler):
920
+ f = lambda x: "color: red" if x > 0 else "color: blue"
921
+ g = lambda x, z: f"color: {z}" if x > 0 else f"color: {z}"
922
+ style1 = styler
923
+ style1.map(f).map(g, z="b").highlight_max()._compute() # = render
924
+ result = style1.export()
925
+ style2 = df.style
926
+ style2.use(result)
927
+ assert style1._todo == style2._todo
928
+ style2.to_html()
929
+
930
+ def test_bad_apply_shape(self):
931
+ df = DataFrame([[1, 2], [3, 4]], index=["A", "B"], columns=["X", "Y"])
932
+
933
+ msg = "resulted in the apply method collapsing to a Series."
934
+ with pytest.raises(ValueError, match=msg):
935
+ df.style._apply(lambda x: "x")
936
+
937
+ msg = "created invalid {} labels"
938
+ with pytest.raises(ValueError, match=msg.format("index")):
939
+ df.style._apply(lambda x: [""])
940
+
941
+ with pytest.raises(ValueError, match=msg.format("index")):
942
+ df.style._apply(lambda x: ["", "", "", ""])
943
+
944
+ with pytest.raises(ValueError, match=msg.format("index")):
945
+ df.style._apply(lambda x: Series(["a:v;", ""], index=["A", "C"]), axis=0)
946
+
947
+ with pytest.raises(ValueError, match=msg.format("columns")):
948
+ df.style._apply(lambda x: ["", "", ""], axis=1)
949
+
950
+ with pytest.raises(ValueError, match=msg.format("columns")):
951
+ df.style._apply(lambda x: Series(["a:v;", ""], index=["X", "Z"]), axis=1)
952
+
953
+ msg = "returned ndarray with wrong shape"
954
+ with pytest.raises(ValueError, match=msg):
955
+ df.style._apply(lambda x: np.array([[""], [""]]), axis=None)
956
+
957
+ def test_apply_bad_return(self):
958
+ def f(x):
959
+ return ""
960
+
961
+ df = DataFrame([[1, 2], [3, 4]])
962
+ msg = (
963
+ "must return a DataFrame or ndarray when passed to `Styler.apply` "
964
+ "with axis=None"
965
+ )
966
+ with pytest.raises(TypeError, match=msg):
967
+ df.style._apply(f, axis=None)
968
+
969
+ @pytest.mark.parametrize("axis", ["index", "columns"])
970
+ def test_apply_bad_labels(self, axis):
971
+ def f(x):
972
+ return DataFrame(**{axis: ["bad", "labels"]})
973
+
974
+ df = DataFrame([[1, 2], [3, 4]])
975
+ msg = f"created invalid {axis} labels."
976
+ with pytest.raises(ValueError, match=msg):
977
+ df.style._apply(f, axis=None)
978
+
979
+ def test_get_level_lengths(self):
980
+ index = MultiIndex.from_product([["a", "b"], [0, 1, 2]])
981
+ expected = {
982
+ (0, 0): 3,
983
+ (0, 3): 3,
984
+ (1, 0): 1,
985
+ (1, 1): 1,
986
+ (1, 2): 1,
987
+ (1, 3): 1,
988
+ (1, 4): 1,
989
+ (1, 5): 1,
990
+ }
991
+ result = _get_level_lengths(index, sparsify=True, max_index=100)
992
+ tm.assert_dict_equal(result, expected)
993
+
994
+ expected = {
995
+ (0, 0): 1,
996
+ (0, 1): 1,
997
+ (0, 2): 1,
998
+ (0, 3): 1,
999
+ (0, 4): 1,
1000
+ (0, 5): 1,
1001
+ (1, 0): 1,
1002
+ (1, 1): 1,
1003
+ (1, 2): 1,
1004
+ (1, 3): 1,
1005
+ (1, 4): 1,
1006
+ (1, 5): 1,
1007
+ }
1008
+ result = _get_level_lengths(index, sparsify=False, max_index=100)
1009
+ tm.assert_dict_equal(result, expected)
1010
+
1011
+ def test_get_level_lengths_un_sorted(self):
1012
+ index = MultiIndex.from_arrays([[1, 1, 2, 1], ["a", "b", "b", "d"]])
1013
+ expected = {
1014
+ (0, 0): 2,
1015
+ (0, 2): 1,
1016
+ (0, 3): 1,
1017
+ (1, 0): 1,
1018
+ (1, 1): 1,
1019
+ (1, 2): 1,
1020
+ (1, 3): 1,
1021
+ }
1022
+ result = _get_level_lengths(index, sparsify=True, max_index=100)
1023
+ tm.assert_dict_equal(result, expected)
1024
+
1025
+ expected = {
1026
+ (0, 0): 1,
1027
+ (0, 1): 1,
1028
+ (0, 2): 1,
1029
+ (0, 3): 1,
1030
+ (1, 0): 1,
1031
+ (1, 1): 1,
1032
+ (1, 2): 1,
1033
+ (1, 3): 1,
1034
+ }
1035
+ result = _get_level_lengths(index, sparsify=False, max_index=100)
1036
+ tm.assert_dict_equal(result, expected)
1037
+
1038
+ def test_mi_sparse_index_names(self, blank_value):
1039
+ # Test the class names and displayed value are correct on rendering MI names
1040
+ df = DataFrame(
1041
+ {"A": [1, 2]},
1042
+ index=MultiIndex.from_arrays(
1043
+ [["a", "a"], [0, 1]], names=["idx_level_0", "idx_level_1"]
1044
+ ),
1045
+ )
1046
+ result = df.style._translate(True, True)
1047
+ head = result["head"][1]
1048
+ expected = [
1049
+ {
1050
+ "class": "index_name level0",
1051
+ "display_value": "idx_level_0",
1052
+ "is_visible": True,
1053
+ },
1054
+ {
1055
+ "class": "index_name level1",
1056
+ "display_value": "idx_level_1",
1057
+ "is_visible": True,
1058
+ },
1059
+ {
1060
+ "class": "blank col0",
1061
+ "display_value": blank_value,
1062
+ "is_visible": True,
1063
+ },
1064
+ ]
1065
+ for i, expected_dict in enumerate(expected):
1066
+ assert expected_dict.items() <= head[i].items()
1067
+
1068
+ def test_mi_sparse_column_names(self, blank_value):
1069
+ df = DataFrame(
1070
+ np.arange(16).reshape(4, 4),
1071
+ index=MultiIndex.from_arrays(
1072
+ [["a", "a", "b", "a"], [0, 1, 1, 2]],
1073
+ names=["idx_level_0", "idx_level_1"],
1074
+ ),
1075
+ columns=MultiIndex.from_arrays(
1076
+ [["C1", "C1", "C2", "C2"], [1, 0, 1, 0]], names=["colnam_0", "colnam_1"]
1077
+ ),
1078
+ )
1079
+ result = Styler(df, cell_ids=False)._translate(True, True)
1080
+
1081
+ for level in [0, 1]:
1082
+ head = result["head"][level]
1083
+ expected = [
1084
+ {
1085
+ "class": "blank",
1086
+ "display_value": blank_value,
1087
+ "is_visible": True,
1088
+ },
1089
+ {
1090
+ "class": f"index_name level{level}",
1091
+ "display_value": f"colnam_{level}",
1092
+ "is_visible": True,
1093
+ },
1094
+ ]
1095
+ for i, expected_dict in enumerate(expected):
1096
+ assert expected_dict.items() <= head[i].items()
1097
+
1098
+ def test_hide_column_headers(self, df, styler):
1099
+ ctx = styler.hide(axis="columns")._translate(True, True)
1100
+ assert len(ctx["head"]) == 0 # no header entries with an unnamed index
1101
+
1102
+ df.index.name = "some_name"
1103
+ ctx = df.style.hide(axis="columns")._translate(True, True)
1104
+ assert len(ctx["head"]) == 1
1105
+ # index names still visible, changed in #42101, reverted in 43404
1106
+
1107
+ def test_hide_single_index(self, df):
1108
+ # GH 14194
1109
+ # single unnamed index
1110
+ ctx = df.style._translate(True, True)
1111
+ assert ctx["body"][0][0]["is_visible"]
1112
+ assert ctx["head"][0][0]["is_visible"]
1113
+ ctx2 = df.style.hide(axis="index")._translate(True, True)
1114
+ assert not ctx2["body"][0][0]["is_visible"]
1115
+ assert not ctx2["head"][0][0]["is_visible"]
1116
+
1117
+ # single named index
1118
+ ctx3 = df.set_index("A").style._translate(True, True)
1119
+ assert ctx3["body"][0][0]["is_visible"]
1120
+ assert len(ctx3["head"]) == 2 # 2 header levels
1121
+ assert ctx3["head"][0][0]["is_visible"]
1122
+
1123
+ ctx4 = df.set_index("A").style.hide(axis="index")._translate(True, True)
1124
+ assert not ctx4["body"][0][0]["is_visible"]
1125
+ assert len(ctx4["head"]) == 1 # only 1 header levels
1126
+ assert not ctx4["head"][0][0]["is_visible"]
1127
+
1128
+ def test_hide_multiindex(self):
1129
+ # GH 14194
1130
+ df = DataFrame(
1131
+ {"A": [1, 2], "B": [1, 2]},
1132
+ index=MultiIndex.from_arrays(
1133
+ [["a", "a"], [0, 1]], names=["idx_level_0", "idx_level_1"]
1134
+ ),
1135
+ )
1136
+ ctx1 = df.style._translate(True, True)
1137
+ # tests for 'a' and '0'
1138
+ assert ctx1["body"][0][0]["is_visible"]
1139
+ assert ctx1["body"][0][1]["is_visible"]
1140
+ # check for blank header rows
1141
+ assert len(ctx1["head"][0]) == 4 # two visible indexes and two data columns
1142
+
1143
+ ctx2 = df.style.hide(axis="index")._translate(True, True)
1144
+ # tests for 'a' and '0'
1145
+ assert not ctx2["body"][0][0]["is_visible"]
1146
+ assert not ctx2["body"][0][1]["is_visible"]
1147
+ # check for blank header rows
1148
+ assert len(ctx2["head"][0]) == 3 # one hidden (col name) and two data columns
1149
+ assert not ctx2["head"][0][0]["is_visible"]
1150
+
1151
+ def test_hide_columns_single_level(self, df):
1152
+ # GH 14194
1153
+ # test hiding single column
1154
+ ctx = df.style._translate(True, True)
1155
+ assert ctx["head"][0][1]["is_visible"]
1156
+ assert ctx["head"][0][1]["display_value"] == "A"
1157
+ assert ctx["head"][0][2]["is_visible"]
1158
+ assert ctx["head"][0][2]["display_value"] == "B"
1159
+ assert ctx["body"][0][1]["is_visible"] # col A, row 1
1160
+ assert ctx["body"][1][2]["is_visible"] # col B, row 1
1161
+
1162
+ ctx = df.style.hide("A", axis="columns")._translate(True, True)
1163
+ assert not ctx["head"][0][1]["is_visible"]
1164
+ assert not ctx["body"][0][1]["is_visible"] # col A, row 1
1165
+ assert ctx["body"][1][2]["is_visible"] # col B, row 1
1166
+
1167
+ # test hiding multiple columns
1168
+ ctx = df.style.hide(["A", "B"], axis="columns")._translate(True, True)
1169
+ assert not ctx["head"][0][1]["is_visible"]
1170
+ assert not ctx["head"][0][2]["is_visible"]
1171
+ assert not ctx["body"][0][1]["is_visible"] # col A, row 1
1172
+ assert not ctx["body"][1][2]["is_visible"] # col B, row 1
1173
+
1174
+ def test_hide_columns_index_mult_levels(self):
1175
+ # GH 14194
1176
+ # setup dataframe with multiple column levels and indices
1177
+ i1 = MultiIndex.from_arrays(
1178
+ [["a", "a"], [0, 1]], names=["idx_level_0", "idx_level_1"]
1179
+ )
1180
+ i2 = MultiIndex.from_arrays(
1181
+ [["b", "b"], [0, 1]], names=["col_level_0", "col_level_1"]
1182
+ )
1183
+ df = DataFrame([[1, 2], [3, 4]], index=i1, columns=i2)
1184
+ ctx = df.style._translate(True, True)
1185
+ # column headers
1186
+ assert ctx["head"][0][2]["is_visible"]
1187
+ assert ctx["head"][1][2]["is_visible"]
1188
+ assert ctx["head"][1][3]["display_value"] == "1"
1189
+ # indices
1190
+ assert ctx["body"][0][0]["is_visible"]
1191
+ # data
1192
+ assert ctx["body"][1][2]["is_visible"]
1193
+ assert ctx["body"][1][2]["display_value"] == "3"
1194
+ assert ctx["body"][1][3]["is_visible"]
1195
+ assert ctx["body"][1][3]["display_value"] == "4"
1196
+
1197
+ # hide top column level, which hides both columns
1198
+ ctx = df.style.hide("b", axis="columns")._translate(True, True)
1199
+ assert not ctx["head"][0][2]["is_visible"] # b
1200
+ assert not ctx["head"][1][2]["is_visible"] # 0
1201
+ assert not ctx["body"][1][2]["is_visible"] # 3
1202
+ assert ctx["body"][0][0]["is_visible"] # index
1203
+
1204
+ # hide first column only
1205
+ ctx = df.style.hide([("b", 0)], axis="columns")._translate(True, True)
1206
+ assert not ctx["head"][0][2]["is_visible"] # b
1207
+ assert ctx["head"][0][3]["is_visible"] # b
1208
+ assert not ctx["head"][1][2]["is_visible"] # 0
1209
+ assert not ctx["body"][1][2]["is_visible"] # 3
1210
+ assert ctx["body"][1][3]["is_visible"]
1211
+ assert ctx["body"][1][3]["display_value"] == "4"
1212
+
1213
+ # hide second column and index
1214
+ ctx = df.style.hide([("b", 1)], axis=1).hide(axis=0)._translate(True, True)
1215
+ assert not ctx["body"][0][0]["is_visible"] # index
1216
+ assert len(ctx["head"][0]) == 3
1217
+ assert ctx["head"][0][1]["is_visible"] # b
1218
+ assert ctx["head"][1][1]["is_visible"] # 0
1219
+ assert not ctx["head"][1][2]["is_visible"] # 1
1220
+ assert not ctx["body"][1][3]["is_visible"] # 4
1221
+ assert ctx["body"][1][2]["is_visible"]
1222
+ assert ctx["body"][1][2]["display_value"] == "3"
1223
+
1224
+ # hide top row level, which hides both rows so body empty
1225
+ ctx = df.style.hide("a", axis="index")._translate(True, True)
1226
+ assert ctx["body"] == []
1227
+
1228
+ # hide first row only
1229
+ ctx = df.style.hide(("a", 0), axis="index")._translate(True, True)
1230
+ for i in [0, 1, 2, 3]:
1231
+ assert "row1" in ctx["body"][0][i]["class"] # row0 not included in body
1232
+ assert ctx["body"][0][i]["is_visible"]
1233
+
1234
+ def test_pipe(self, df):
1235
+ def set_caption_from_template(styler, a, b):
1236
+ return styler.set_caption(f"Dataframe with a = {a} and b = {b}")
1237
+
1238
+ styler = df.style.pipe(set_caption_from_template, "A", b="B")
1239
+ assert "Dataframe with a = A and b = B" in styler.to_html()
1240
+
1241
+ # Test with an argument that is a (callable, keyword_name) pair.
1242
+ def f(a, b, styler):
1243
+ return (a, b, styler)
1244
+
1245
+ styler = df.style
1246
+ result = styler.pipe((f, "styler"), a=1, b=2)
1247
+ assert result == (1, 2, styler)
1248
+
1249
+ def test_no_cell_ids(self):
1250
+ # GH 35588
1251
+ # GH 35663
1252
+ df = DataFrame(data=[[0]])
1253
+ styler = Styler(df, uuid="_", cell_ids=False)
1254
+ styler.to_html()
1255
+ s = styler.to_html() # render twice to ensure ctx is not updated
1256
+ assert s.find('<td class="data row0 col0" >') != -1
1257
+
1258
+ @pytest.mark.parametrize(
1259
+ "classes",
1260
+ [
1261
+ DataFrame(
1262
+ data=[["", "test-class"], [np.nan, None]],
1263
+ columns=["A", "B"],
1264
+ index=["a", "b"],
1265
+ ),
1266
+ DataFrame(data=[["test-class"]], columns=["B"], index=["a"]),
1267
+ DataFrame(data=[["test-class", "unused"]], columns=["B", "C"], index=["a"]),
1268
+ ],
1269
+ )
1270
+ def test_set_data_classes(self, classes):
1271
+ # GH 36159
1272
+ df = DataFrame(data=[[0, 1], [2, 3]], columns=["A", "B"], index=["a", "b"])
1273
+ s = Styler(df, uuid_len=0, cell_ids=False).set_td_classes(classes).to_html()
1274
+ assert '<td class="data row0 col0" >0</td>' in s
1275
+ assert '<td class="data row0 col1 test-class" >1</td>' in s
1276
+ assert '<td class="data row1 col0" >2</td>' in s
1277
+ assert '<td class="data row1 col1" >3</td>' in s
1278
+ # GH 39317
1279
+ s = Styler(df, uuid_len=0, cell_ids=True).set_td_classes(classes).to_html()
1280
+ assert '<td id="T__row0_col0" class="data row0 col0" >0</td>' in s
1281
+ assert '<td id="T__row0_col1" class="data row0 col1 test-class" >1</td>' in s
1282
+ assert '<td id="T__row1_col0" class="data row1 col0" >2</td>' in s
1283
+ assert '<td id="T__row1_col1" class="data row1 col1" >3</td>' in s
1284
+
1285
+ def test_set_data_classes_reindex(self):
1286
+ # GH 39317
1287
+ df = DataFrame(
1288
+ data=[[0, 1, 2], [3, 4, 5], [6, 7, 8]], columns=[0, 1, 2], index=[0, 1, 2]
1289
+ )
1290
+ classes = DataFrame(
1291
+ data=[["mi", "ma"], ["mu", "mo"]],
1292
+ columns=[0, 2],
1293
+ index=[0, 2],
1294
+ )
1295
+ s = Styler(df, uuid_len=0).set_td_classes(classes).to_html()
1296
+ assert '<td id="T__row0_col0" class="data row0 col0 mi" >0</td>' in s
1297
+ assert '<td id="T__row0_col2" class="data row0 col2 ma" >2</td>' in s
1298
+ assert '<td id="T__row1_col1" class="data row1 col1" >4</td>' in s
1299
+ assert '<td id="T__row2_col0" class="data row2 col0 mu" >6</td>' in s
1300
+ assert '<td id="T__row2_col2" class="data row2 col2 mo" >8</td>' in s
1301
+
1302
+ def test_chaining_table_styles(self):
1303
+ # GH 35607
1304
+ df = DataFrame(data=[[0, 1], [1, 2]], columns=["A", "B"])
1305
+ styler = df.style.set_table_styles(
1306
+ [{"selector": "", "props": [("background-color", "yellow")]}]
1307
+ ).set_table_styles(
1308
+ [{"selector": ".col0", "props": [("background-color", "blue")]}],
1309
+ overwrite=False,
1310
+ )
1311
+ assert len(styler.table_styles) == 2
1312
+
1313
+ def test_column_and_row_styling(self):
1314
+ # GH 35607
1315
+ df = DataFrame(data=[[0, 1], [1, 2]], columns=["A", "B"])
1316
+ s = Styler(df, uuid_len=0)
1317
+ s = s.set_table_styles({"A": [{"selector": "", "props": [("color", "blue")]}]})
1318
+ assert "#T_ .col0 {\n color: blue;\n}" in s.to_html()
1319
+ s = s.set_table_styles(
1320
+ {0: [{"selector": "", "props": [("color", "blue")]}]}, axis=1
1321
+ )
1322
+ assert "#T_ .row0 {\n color: blue;\n}" in s.to_html()
1323
+
1324
+ @pytest.mark.parametrize("len_", [1, 5, 32, 33, 100])
1325
+ def test_uuid_len(self, len_):
1326
+ # GH 36345
1327
+ df = DataFrame(data=[["A"]])
1328
+ s = Styler(df, uuid_len=len_, cell_ids=False).to_html()
1329
+ strt = s.find('id="T_')
1330
+ end = s[strt + 6 :].find('"')
1331
+ if len_ > 32:
1332
+ assert end == 32
1333
+ else:
1334
+ assert end == len_
1335
+
1336
+ @pytest.mark.parametrize("len_", [-2, "bad", None])
1337
+ def test_uuid_len_raises(self, len_):
1338
+ # GH 36345
1339
+ df = DataFrame(data=[["A"]])
1340
+ msg = "``uuid_len`` must be an integer in range \\[0, 32\\]."
1341
+ with pytest.raises(TypeError, match=msg):
1342
+ Styler(df, uuid_len=len_, cell_ids=False).to_html()
1343
+
1344
+ @pytest.mark.parametrize(
1345
+ "slc",
1346
+ [
1347
+ IndexSlice[:, :],
1348
+ IndexSlice[:, 1],
1349
+ IndexSlice[1, :],
1350
+ IndexSlice[[1], [1]],
1351
+ IndexSlice[1, [1]],
1352
+ IndexSlice[[1], 1],
1353
+ IndexSlice[1],
1354
+ IndexSlice[1, 1],
1355
+ slice(None, None, None),
1356
+ [0, 1],
1357
+ np.array([0, 1]),
1358
+ Series([0, 1]),
1359
+ ],
1360
+ )
1361
+ def test_non_reducing_slice(self, slc):
1362
+ df = DataFrame([[0, 1], [2, 3]])
1363
+
1364
+ tslice_ = non_reducing_slice(slc)
1365
+ assert isinstance(df.loc[tslice_], DataFrame)
1366
+
1367
+ @pytest.mark.parametrize("box", [list, Series, np.array])
1368
+ def test_list_slice(self, box):
1369
+ # like dataframe getitem
1370
+ subset = box(["A"])
1371
+
1372
+ df = DataFrame({"A": [1, 2], "B": [3, 4]}, index=["A", "B"])
1373
+ expected = IndexSlice[:, ["A"]]
1374
+
1375
+ result = non_reducing_slice(subset)
1376
+ tm.assert_frame_equal(df.loc[result], df.loc[expected])
1377
+
1378
+ def test_non_reducing_slice_on_multiindex(self):
1379
+ # GH 19861
1380
+ dic = {
1381
+ ("a", "d"): [1, 4],
1382
+ ("a", "c"): [2, 3],
1383
+ ("b", "c"): [3, 2],
1384
+ ("b", "d"): [4, 1],
1385
+ }
1386
+ df = DataFrame(dic, index=[0, 1])
1387
+ idx = IndexSlice
1388
+ slice_ = idx[:, idx["b", "d"]]
1389
+ tslice_ = non_reducing_slice(slice_)
1390
+
1391
+ result = df.loc[tslice_]
1392
+ expected = DataFrame({("b", "d"): [4, 1]})
1393
+ tm.assert_frame_equal(result, expected)
1394
+
1395
+ @pytest.mark.parametrize(
1396
+ "slice_",
1397
+ [
1398
+ IndexSlice[:, :],
1399
+ # check cols
1400
+ IndexSlice[:, IndexSlice[["a"]]], # inferred deeper need list
1401
+ IndexSlice[:, IndexSlice[["a"], ["c"]]], # inferred deeper need list
1402
+ IndexSlice[:, IndexSlice["a", "c", :]],
1403
+ IndexSlice[:, IndexSlice["a", :, "e"]],
1404
+ IndexSlice[:, IndexSlice[:, "c", "e"]],
1405
+ IndexSlice[:, IndexSlice["a", ["c", "d"], :]], # check list
1406
+ IndexSlice[:, IndexSlice["a", ["c", "d", "-"], :]], # don't allow missing
1407
+ IndexSlice[:, IndexSlice["a", ["c", "d", "-"], "e"]], # no slice
1408
+ # check rows
1409
+ IndexSlice[IndexSlice[["U"]], :], # inferred deeper need list
1410
+ IndexSlice[IndexSlice[["U"], ["W"]], :], # inferred deeper need list
1411
+ IndexSlice[IndexSlice["U", "W", :], :],
1412
+ IndexSlice[IndexSlice["U", :, "Y"], :],
1413
+ IndexSlice[IndexSlice[:, "W", "Y"], :],
1414
+ IndexSlice[IndexSlice[:, "W", ["Y", "Z"]], :], # check list
1415
+ IndexSlice[IndexSlice[:, "W", ["Y", "Z", "-"]], :], # don't allow missing
1416
+ IndexSlice[IndexSlice["U", "W", ["Y", "Z", "-"]], :], # no slice
1417
+ # check simultaneous
1418
+ IndexSlice[IndexSlice[:, "W", "Y"], IndexSlice["a", "c", :]],
1419
+ ],
1420
+ )
1421
+ def test_non_reducing_multi_slice_on_multiindex(self, slice_):
1422
+ # GH 33562
1423
+ cols = MultiIndex.from_product([["a", "b"], ["c", "d"], ["e", "f"]])
1424
+ idxs = MultiIndex.from_product([["U", "V"], ["W", "X"], ["Y", "Z"]])
1425
+ df = DataFrame(np.arange(64).reshape(8, 8), columns=cols, index=idxs)
1426
+
1427
+ for lvl in [0, 1]:
1428
+ key = slice_[lvl]
1429
+ if isinstance(key, tuple):
1430
+ for subkey in key:
1431
+ if isinstance(subkey, list) and "-" in subkey:
1432
+ # not present in the index level, raises KeyError since 2.0
1433
+ with pytest.raises(KeyError, match="-"):
1434
+ df.loc[slice_]
1435
+ return
1436
+
1437
+ expected = df.loc[slice_]
1438
+ result = df.loc[non_reducing_slice(slice_)]
1439
+ tm.assert_frame_equal(result, expected)
1440
+
1441
+
1442
+ def test_hidden_index_names(mi_df):
1443
+ mi_df.index.names = ["Lev0", "Lev1"]
1444
+ mi_styler = mi_df.style
1445
+ ctx = mi_styler._translate(True, True)
1446
+ assert len(ctx["head"]) == 3 # 2 column index levels + 1 index names row
1447
+
1448
+ mi_styler.hide(axis="index", names=True)
1449
+ ctx = mi_styler._translate(True, True)
1450
+ assert len(ctx["head"]) == 2 # index names row is unparsed
1451
+ for i in range(4):
1452
+ assert ctx["body"][0][i]["is_visible"] # 2 index levels + 2 data values visible
1453
+
1454
+ mi_styler.hide(axis="index", level=1)
1455
+ ctx = mi_styler._translate(True, True)
1456
+ assert len(ctx["head"]) == 2 # index names row is still hidden
1457
+ assert ctx["body"][0][0]["is_visible"] is True
1458
+ assert ctx["body"][0][1]["is_visible"] is False
1459
+
1460
+
1461
+ def test_hidden_column_names(mi_df):
1462
+ mi_df.columns.names = ["Lev0", "Lev1"]
1463
+ mi_styler = mi_df.style
1464
+ ctx = mi_styler._translate(True, True)
1465
+ assert ctx["head"][0][1]["display_value"] == "Lev0"
1466
+ assert ctx["head"][1][1]["display_value"] == "Lev1"
1467
+
1468
+ mi_styler.hide(names=True, axis="columns")
1469
+ ctx = mi_styler._translate(True, True)
1470
+ assert ctx["head"][0][1]["display_value"] == "&nbsp;"
1471
+ assert ctx["head"][1][1]["display_value"] == "&nbsp;"
1472
+
1473
+ mi_styler.hide(level=0, axis="columns")
1474
+ ctx = mi_styler._translate(True, True)
1475
+ assert len(ctx["head"]) == 1 # no index names and only one visible column headers
1476
+ assert ctx["head"][0][1]["display_value"] == "&nbsp;"
1477
+
1478
+
1479
+ @pytest.mark.parametrize("caption", [1, ("a", "b", "c"), (1, "s")])
1480
+ def test_caption_raises(mi_styler, caption):
1481
+ msg = "`caption` must be either a string or 2-tuple of strings."
1482
+ with pytest.raises(ValueError, match=msg):
1483
+ mi_styler.set_caption(caption)
1484
+
1485
+
1486
+ def test_hiding_headers_over_index_no_sparsify():
1487
+ # GH 43464
1488
+ midx = MultiIndex.from_product([[1, 2], ["a", "a", "b"]])
1489
+ df = DataFrame(9, index=midx, columns=[0])
1490
+ ctx = df.style._translate(False, False)
1491
+ assert len(ctx["body"]) == 6
1492
+ ctx = df.style.hide((1, "a"), axis=0)._translate(False, False)
1493
+ assert len(ctx["body"]) == 4
1494
+ assert "row2" in ctx["body"][0][0]["class"]
1495
+
1496
+
1497
+ def test_hiding_headers_over_columns_no_sparsify():
1498
+ # GH 43464
1499
+ midx = MultiIndex.from_product([[1, 2], ["a", "a", "b"]])
1500
+ df = DataFrame(9, columns=midx, index=[0])
1501
+ ctx = df.style._translate(False, False)
1502
+ for ix in [(0, 1), (0, 2), (1, 1), (1, 2)]:
1503
+ assert ctx["head"][ix[0]][ix[1]]["is_visible"] is True
1504
+ ctx = df.style.hide((1, "a"), axis="columns")._translate(False, False)
1505
+ for ix in [(0, 1), (0, 2), (1, 1), (1, 2)]:
1506
+ assert ctx["head"][ix[0]][ix[1]]["is_visible"] is False
1507
+
1508
+
1509
+ def test_get_level_lengths_mi_hidden():
1510
+ # GH 43464
1511
+ index = MultiIndex.from_arrays([[1, 1, 1, 2, 2, 2], ["a", "a", "b", "a", "a", "b"]])
1512
+ expected = {
1513
+ (0, 2): 1,
1514
+ (0, 3): 1,
1515
+ (0, 4): 1,
1516
+ (0, 5): 1,
1517
+ (1, 2): 1,
1518
+ (1, 3): 1,
1519
+ (1, 4): 1,
1520
+ (1, 5): 1,
1521
+ }
1522
+ result = _get_level_lengths(
1523
+ index,
1524
+ sparsify=False,
1525
+ max_index=100,
1526
+ hidden_elements=[0, 1, 0, 1], # hidden element can repeat if duplicated index
1527
+ )
1528
+ tm.assert_dict_equal(result, expected)
1529
+
1530
+
1531
+ def test_row_trimming_hide_index():
1532
+ # gh 43703
1533
+ df = DataFrame([[1], [2], [3], [4], [5]])
1534
+ with option_context("styler.render.max_rows", 2):
1535
+ ctx = df.style.hide([0, 1], axis="index")._translate(True, True)
1536
+ assert len(ctx["body"]) == 3
1537
+ for r, val in enumerate(["3", "4", "..."]):
1538
+ assert ctx["body"][r][1]["display_value"] == val
1539
+
1540
+
1541
+ def test_row_trimming_hide_index_mi():
1542
+ # gh 44247
1543
+ df = DataFrame([[1], [2], [3], [4], [5]])
1544
+ df.index = MultiIndex.from_product([[0], [0, 1, 2, 3, 4]])
1545
+ with option_context("styler.render.max_rows", 2):
1546
+ ctx = df.style.hide([(0, 0), (0, 1)], axis="index")._translate(True, True)
1547
+ assert len(ctx["body"]) == 3
1548
+
1549
+ # level 0 index headers (sparsified)
1550
+ assert {"value": 0, "attributes": 'rowspan="2"', "is_visible": True}.items() <= ctx[
1551
+ "body"
1552
+ ][0][0].items()
1553
+ assert {"value": 0, "attributes": "", "is_visible": False}.items() <= ctx["body"][
1554
+ 1
1555
+ ][0].items()
1556
+ assert {"value": "...", "is_visible": True}.items() <= ctx["body"][2][0].items()
1557
+
1558
+ for r, val in enumerate(["2", "3", "..."]):
1559
+ assert ctx["body"][r][1]["display_value"] == val # level 1 index headers
1560
+ for r, val in enumerate(["3", "4", "..."]):
1561
+ assert ctx["body"][r][2]["display_value"] == val # data values
1562
+
1563
+
1564
+ def test_col_trimming_hide_columns():
1565
+ # gh 44272
1566
+ df = DataFrame([[1, 2, 3, 4, 5]])
1567
+ with option_context("styler.render.max_columns", 2):
1568
+ ctx = df.style.hide([0, 1], axis="columns")._translate(True, True)
1569
+
1570
+ assert len(ctx["head"][0]) == 6 # blank, [0, 1 (hidden)], [2 ,3 (visible)], + trim
1571
+ for c, vals in enumerate([(1, False), (2, True), (3, True), ("...", True)]):
1572
+ assert ctx["head"][0][c + 2]["value"] == vals[0]
1573
+ assert ctx["head"][0][c + 2]["is_visible"] == vals[1]
1574
+
1575
+ assert len(ctx["body"][0]) == 6 # index + 2 hidden + 2 visible + trimming col
1576
+
1577
+
1578
+ def test_no_empty_apply(mi_styler):
1579
+ # 45313
1580
+ mi_styler.apply(lambda s: ["a:v;"] * 2, subset=[False, False])
1581
+ mi_styler._compute()
1582
+
1583
+
1584
+ @pytest.mark.parametrize("format", ["html", "latex", "string"])
1585
+ def test_output_buffer(mi_styler, format):
1586
+ # gh 47053
1587
+ with tm.ensure_clean(f"delete_me.{format}") as f:
1588
+ getattr(mi_styler, f"to_{format}")(f)
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/test_to_latex.py ADDED
@@ -0,0 +1,1090 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from textwrap import dedent
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ from pandas import (
7
+ DataFrame,
8
+ MultiIndex,
9
+ Series,
10
+ option_context,
11
+ )
12
+
13
+ pytest.importorskip("jinja2")
14
+ from pandas.io.formats.style import Styler
15
+ from pandas.io.formats.style_render import (
16
+ _parse_latex_cell_styles,
17
+ _parse_latex_css_conversion,
18
+ _parse_latex_header_span,
19
+ _parse_latex_table_styles,
20
+ _parse_latex_table_wrapping,
21
+ )
22
+
23
+
24
+ @pytest.fixture
25
+ def df():
26
+ return DataFrame(
27
+ {"A": [0, 1], "B": [-0.61, -1.22], "C": Series(["ab", "cd"], dtype=object)}
28
+ )
29
+
30
+
31
+ @pytest.fixture
32
+ def df_ext():
33
+ return DataFrame(
34
+ {"A": [0, 1, 2], "B": [-0.61, -1.22, -2.22], "C": ["ab", "cd", "de"]}
35
+ )
36
+
37
+
38
+ @pytest.fixture
39
+ def styler(df):
40
+ return Styler(df, uuid_len=0, precision=2)
41
+
42
+
43
+ def test_minimal_latex_tabular(styler):
44
+ expected = dedent(
45
+ """\
46
+ \\begin{tabular}{lrrl}
47
+ & A & B & C \\\\
48
+ 0 & 0 & -0.61 & ab \\\\
49
+ 1 & 1 & -1.22 & cd \\\\
50
+ \\end{tabular}
51
+ """
52
+ )
53
+ assert styler.to_latex() == expected
54
+
55
+
56
+ def test_tabular_hrules(styler):
57
+ expected = dedent(
58
+ """\
59
+ \\begin{tabular}{lrrl}
60
+ \\toprule
61
+ & A & B & C \\\\
62
+ \\midrule
63
+ 0 & 0 & -0.61 & ab \\\\
64
+ 1 & 1 & -1.22 & cd \\\\
65
+ \\bottomrule
66
+ \\end{tabular}
67
+ """
68
+ )
69
+ assert styler.to_latex(hrules=True) == expected
70
+
71
+
72
+ def test_tabular_custom_hrules(styler):
73
+ styler.set_table_styles(
74
+ [
75
+ {"selector": "toprule", "props": ":hline"},
76
+ {"selector": "bottomrule", "props": ":otherline"},
77
+ ]
78
+ ) # no midrule
79
+ expected = dedent(
80
+ """\
81
+ \\begin{tabular}{lrrl}
82
+ \\hline
83
+ & A & B & C \\\\
84
+ 0 & 0 & -0.61 & ab \\\\
85
+ 1 & 1 & -1.22 & cd \\\\
86
+ \\otherline
87
+ \\end{tabular}
88
+ """
89
+ )
90
+ assert styler.to_latex() == expected
91
+
92
+
93
+ def test_column_format(styler):
94
+ # default setting is already tested in `test_latex_minimal_tabular`
95
+ styler.set_table_styles([{"selector": "column_format", "props": ":cccc"}])
96
+
97
+ assert "\\begin{tabular}{rrrr}" in styler.to_latex(column_format="rrrr")
98
+ styler.set_table_styles([{"selector": "column_format", "props": ":r|r|cc"}])
99
+ assert "\\begin{tabular}{r|r|cc}" in styler.to_latex()
100
+
101
+
102
+ def test_siunitx_cols(styler):
103
+ expected = dedent(
104
+ """\
105
+ \\begin{tabular}{lSSl}
106
+ {} & {A} & {B} & {C} \\\\
107
+ 0 & 0 & -0.61 & ab \\\\
108
+ 1 & 1 & -1.22 & cd \\\\
109
+ \\end{tabular}
110
+ """
111
+ )
112
+ assert styler.to_latex(siunitx=True) == expected
113
+
114
+
115
+ def test_position(styler):
116
+ assert "\\begin{table}[h!]" in styler.to_latex(position="h!")
117
+ assert "\\end{table}" in styler.to_latex(position="h!")
118
+ styler.set_table_styles([{"selector": "position", "props": ":b!"}])
119
+ assert "\\begin{table}[b!]" in styler.to_latex()
120
+ assert "\\end{table}" in styler.to_latex()
121
+
122
+
123
+ @pytest.mark.parametrize("env", [None, "longtable"])
124
+ def test_label(styler, env):
125
+ assert "\n\\label{text}" in styler.to_latex(label="text", environment=env)
126
+ styler.set_table_styles([{"selector": "label", "props": ":{more Β§text}"}])
127
+ assert "\n\\label{more :text}" in styler.to_latex(environment=env)
128
+
129
+
130
+ def test_position_float_raises(styler):
131
+ msg = "`position_float` should be one of 'raggedright', 'raggedleft', 'centering',"
132
+ with pytest.raises(ValueError, match=msg):
133
+ styler.to_latex(position_float="bad_string")
134
+
135
+ msg = "`position_float` cannot be used in 'longtable' `environment`"
136
+ with pytest.raises(ValueError, match=msg):
137
+ styler.to_latex(position_float="centering", environment="longtable")
138
+
139
+
140
+ @pytest.mark.parametrize("label", [(None, ""), ("text", "\\label{text}")])
141
+ @pytest.mark.parametrize("position", [(None, ""), ("h!", "{table}[h!]")])
142
+ @pytest.mark.parametrize("caption", [(None, ""), ("text", "\\caption{text}")])
143
+ @pytest.mark.parametrize("column_format", [(None, ""), ("rcrl", "{tabular}{rcrl}")])
144
+ @pytest.mark.parametrize("position_float", [(None, ""), ("centering", "\\centering")])
145
+ def test_kwargs_combinations(
146
+ styler, label, position, caption, column_format, position_float
147
+ ):
148
+ result = styler.to_latex(
149
+ label=label[0],
150
+ position=position[0],
151
+ caption=caption[0],
152
+ column_format=column_format[0],
153
+ position_float=position_float[0],
154
+ )
155
+ assert label[1] in result
156
+ assert position[1] in result
157
+ assert caption[1] in result
158
+ assert column_format[1] in result
159
+ assert position_float[1] in result
160
+
161
+
162
+ def test_custom_table_styles(styler):
163
+ styler.set_table_styles(
164
+ [
165
+ {"selector": "mycommand", "props": ":{myoptions}"},
166
+ {"selector": "mycommand2", "props": ":{myoptions2}"},
167
+ ]
168
+ )
169
+ expected = dedent(
170
+ """\
171
+ \\begin{table}
172
+ \\mycommand{myoptions}
173
+ \\mycommand2{myoptions2}
174
+ """
175
+ )
176
+ assert expected in styler.to_latex()
177
+
178
+
179
+ def test_cell_styling(styler):
180
+ styler.highlight_max(props="itshape:;Huge:--wrap;")
181
+ expected = dedent(
182
+ """\
183
+ \\begin{tabular}{lrrl}
184
+ & A & B & C \\\\
185
+ 0 & 0 & \\itshape {\\Huge -0.61} & ab \\\\
186
+ 1 & \\itshape {\\Huge 1} & -1.22 & \\itshape {\\Huge cd} \\\\
187
+ \\end{tabular}
188
+ """
189
+ )
190
+ assert expected == styler.to_latex()
191
+
192
+
193
+ def test_multiindex_columns(df):
194
+ cidx = MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("B", "c")])
195
+ df.columns = cidx
196
+ expected = dedent(
197
+ """\
198
+ \\begin{tabular}{lrrl}
199
+ & \\multicolumn{2}{r}{A} & B \\\\
200
+ & a & b & c \\\\
201
+ 0 & 0 & -0.61 & ab \\\\
202
+ 1 & 1 & -1.22 & cd \\\\
203
+ \\end{tabular}
204
+ """
205
+ )
206
+ s = df.style.format(precision=2)
207
+ assert expected == s.to_latex()
208
+
209
+ # non-sparse
210
+ expected = dedent(
211
+ """\
212
+ \\begin{tabular}{lrrl}
213
+ & A & A & B \\\\
214
+ & a & b & c \\\\
215
+ 0 & 0 & -0.61 & ab \\\\
216
+ 1 & 1 & -1.22 & cd \\\\
217
+ \\end{tabular}
218
+ """
219
+ )
220
+ s = df.style.format(precision=2)
221
+ assert expected == s.to_latex(sparse_columns=False)
222
+
223
+
224
+ def test_multiindex_row(df_ext):
225
+ ridx = MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("B", "c")])
226
+ df_ext.index = ridx
227
+ expected = dedent(
228
+ """\
229
+ \\begin{tabular}{llrrl}
230
+ & & A & B & C \\\\
231
+ \\multirow[c]{2}{*}{A} & a & 0 & -0.61 & ab \\\\
232
+ & b & 1 & -1.22 & cd \\\\
233
+ B & c & 2 & -2.22 & de \\\\
234
+ \\end{tabular}
235
+ """
236
+ )
237
+ styler = df_ext.style.format(precision=2)
238
+ result = styler.to_latex()
239
+ assert expected == result
240
+
241
+ # non-sparse
242
+ expected = dedent(
243
+ """\
244
+ \\begin{tabular}{llrrl}
245
+ & & A & B & C \\\\
246
+ A & a & 0 & -0.61 & ab \\\\
247
+ A & b & 1 & -1.22 & cd \\\\
248
+ B & c & 2 & -2.22 & de \\\\
249
+ \\end{tabular}
250
+ """
251
+ )
252
+ result = styler.to_latex(sparse_index=False)
253
+ assert expected == result
254
+
255
+
256
+ def test_multirow_naive(df_ext):
257
+ ridx = MultiIndex.from_tuples([("X", "x"), ("X", "y"), ("Y", "z")])
258
+ df_ext.index = ridx
259
+ expected = dedent(
260
+ """\
261
+ \\begin{tabular}{llrrl}
262
+ & & A & B & C \\\\
263
+ X & x & 0 & -0.61 & ab \\\\
264
+ & y & 1 & -1.22 & cd \\\\
265
+ Y & z & 2 & -2.22 & de \\\\
266
+ \\end{tabular}
267
+ """
268
+ )
269
+ styler = df_ext.style.format(precision=2)
270
+ result = styler.to_latex(multirow_align="naive")
271
+ assert expected == result
272
+
273
+
274
+ def test_multiindex_row_and_col(df_ext):
275
+ cidx = MultiIndex.from_tuples([("Z", "a"), ("Z", "b"), ("Y", "c")])
276
+ ridx = MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("B", "c")])
277
+ df_ext.index, df_ext.columns = ridx, cidx
278
+ expected = dedent(
279
+ """\
280
+ \\begin{tabular}{llrrl}
281
+ & & \\multicolumn{2}{l}{Z} & Y \\\\
282
+ & & a & b & c \\\\
283
+ \\multirow[b]{2}{*}{A} & a & 0 & -0.61 & ab \\\\
284
+ & b & 1 & -1.22 & cd \\\\
285
+ B & c & 2 & -2.22 & de \\\\
286
+ \\end{tabular}
287
+ """
288
+ )
289
+ styler = df_ext.style.format(precision=2)
290
+ result = styler.to_latex(multirow_align="b", multicol_align="l")
291
+ assert result == expected
292
+
293
+ # non-sparse
294
+ expected = dedent(
295
+ """\
296
+ \\begin{tabular}{llrrl}
297
+ & & Z & Z & Y \\\\
298
+ & & a & b & c \\\\
299
+ A & a & 0 & -0.61 & ab \\\\
300
+ A & b & 1 & -1.22 & cd \\\\
301
+ B & c & 2 & -2.22 & de \\\\
302
+ \\end{tabular}
303
+ """
304
+ )
305
+ result = styler.to_latex(sparse_index=False, sparse_columns=False)
306
+ assert result == expected
307
+
308
+
309
+ @pytest.mark.parametrize(
310
+ "multicol_align, siunitx, header",
311
+ [
312
+ ("naive-l", False, " & A & &"),
313
+ ("naive-r", False, " & & & A"),
314
+ ("naive-l", True, "{} & {A} & {} & {}"),
315
+ ("naive-r", True, "{} & {} & {} & {A}"),
316
+ ],
317
+ )
318
+ def test_multicol_naive(df, multicol_align, siunitx, header):
319
+ ridx = MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("A", "c")])
320
+ df.columns = ridx
321
+ level1 = " & a & b & c" if not siunitx else "{} & {a} & {b} & {c}"
322
+ col_format = "lrrl" if not siunitx else "lSSl"
323
+ expected = dedent(
324
+ f"""\
325
+ \\begin{{tabular}}{{{col_format}}}
326
+ {header} \\\\
327
+ {level1} \\\\
328
+ 0 & 0 & -0.61 & ab \\\\
329
+ 1 & 1 & -1.22 & cd \\\\
330
+ \\end{{tabular}}
331
+ """
332
+ )
333
+ styler = df.style.format(precision=2)
334
+ result = styler.to_latex(multicol_align=multicol_align, siunitx=siunitx)
335
+ assert expected == result
336
+
337
+
338
+ def test_multi_options(df_ext):
339
+ cidx = MultiIndex.from_tuples([("Z", "a"), ("Z", "b"), ("Y", "c")])
340
+ ridx = MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("B", "c")])
341
+ df_ext.index, df_ext.columns = ridx, cidx
342
+ styler = df_ext.style.format(precision=2)
343
+
344
+ expected = dedent(
345
+ """\
346
+ & & \\multicolumn{2}{r}{Z} & Y \\\\
347
+ & & a & b & c \\\\
348
+ \\multirow[c]{2}{*}{A} & a & 0 & -0.61 & ab \\\\
349
+ """
350
+ )
351
+ result = styler.to_latex()
352
+ assert expected in result
353
+
354
+ with option_context("styler.latex.multicol_align", "l"):
355
+ assert " & & \\multicolumn{2}{l}{Z} & Y \\\\" in styler.to_latex()
356
+
357
+ with option_context("styler.latex.multirow_align", "b"):
358
+ assert "\\multirow[b]{2}{*}{A} & a & 0 & -0.61 & ab \\\\" in styler.to_latex()
359
+
360
+
361
+ def test_multiindex_columns_hidden():
362
+ df = DataFrame([[1, 2, 3, 4]])
363
+ df.columns = MultiIndex.from_tuples([("A", 1), ("A", 2), ("A", 3), ("B", 1)])
364
+ s = df.style
365
+ assert "{tabular}{lrrrr}" in s.to_latex()
366
+ s.set_table_styles([]) # reset the position command
367
+ s.hide([("A", 2)], axis="columns")
368
+ assert "{tabular}{lrrr}" in s.to_latex()
369
+
370
+
371
+ @pytest.mark.parametrize(
372
+ "option, value",
373
+ [
374
+ ("styler.sparse.index", True),
375
+ ("styler.sparse.index", False),
376
+ ("styler.sparse.columns", True),
377
+ ("styler.sparse.columns", False),
378
+ ],
379
+ )
380
+ def test_sparse_options(df_ext, option, value):
381
+ cidx = MultiIndex.from_tuples([("Z", "a"), ("Z", "b"), ("Y", "c")])
382
+ ridx = MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("B", "c")])
383
+ df_ext.index, df_ext.columns = ridx, cidx
384
+ styler = df_ext.style
385
+
386
+ latex1 = styler.to_latex()
387
+ with option_context(option, value):
388
+ latex2 = styler.to_latex()
389
+ assert (latex1 == latex2) is value
390
+
391
+
392
+ def test_hidden_index(styler):
393
+ styler.hide(axis="index")
394
+ expected = dedent(
395
+ """\
396
+ \\begin{tabular}{rrl}
397
+ A & B & C \\\\
398
+ 0 & -0.61 & ab \\\\
399
+ 1 & -1.22 & cd \\\\
400
+ \\end{tabular}
401
+ """
402
+ )
403
+ assert styler.to_latex() == expected
404
+
405
+
406
+ @pytest.mark.parametrize("environment", ["table", "figure*", None])
407
+ def test_comprehensive(df_ext, environment):
408
+ # test as many low level features simultaneously as possible
409
+ cidx = MultiIndex.from_tuples([("Z", "a"), ("Z", "b"), ("Y", "c")])
410
+ ridx = MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("B", "c")])
411
+ df_ext.index, df_ext.columns = ridx, cidx
412
+ stlr = df_ext.style
413
+ stlr.set_caption("mycap")
414
+ stlr.set_table_styles(
415
+ [
416
+ {"selector": "label", "props": ":{figΒ§item}"},
417
+ {"selector": "position", "props": ":h!"},
418
+ {"selector": "position_float", "props": ":centering"},
419
+ {"selector": "column_format", "props": ":rlrlr"},
420
+ {"selector": "toprule", "props": ":toprule"},
421
+ {"selector": "midrule", "props": ":midrule"},
422
+ {"selector": "bottomrule", "props": ":bottomrule"},
423
+ {"selector": "rowcolors", "props": ":{3}{pink}{}"}, # custom command
424
+ ]
425
+ )
426
+ stlr.highlight_max(axis=0, props="textbf:--rwrap;cellcolor:[rgb]{1,1,0.6}--rwrap")
427
+ stlr.highlight_max(axis=None, props="Huge:--wrap;", subset=[("Z", "a"), ("Z", "b")])
428
+
429
+ expected = (
430
+ """\
431
+ \\begin{table}[h!]
432
+ \\centering
433
+ \\caption{mycap}
434
+ \\label{fig:item}
435
+ \\rowcolors{3}{pink}{}
436
+ \\begin{tabular}{rlrlr}
437
+ \\toprule
438
+ & & \\multicolumn{2}{r}{Z} & Y \\\\
439
+ & & a & b & c \\\\
440
+ \\midrule
441
+ \\multirow[c]{2}{*}{A} & a & 0 & \\textbf{\\cellcolor[rgb]{1,1,0.6}{-0.61}} & ab \\\\
442
+ & b & 1 & -1.22 & cd \\\\
443
+ B & c & \\textbf{\\cellcolor[rgb]{1,1,0.6}{{\\Huge 2}}} & -2.22 & """
444
+ """\
445
+ \\textbf{\\cellcolor[rgb]{1,1,0.6}{de}} \\\\
446
+ \\bottomrule
447
+ \\end{tabular}
448
+ \\end{table}
449
+ """
450
+ ).replace("table", environment if environment else "table")
451
+ result = stlr.format(precision=2).to_latex(environment=environment)
452
+ assert result == expected
453
+
454
+
455
+ def test_environment_option(styler):
456
+ with option_context("styler.latex.environment", "bar-env"):
457
+ assert "\\begin{bar-env}" in styler.to_latex()
458
+ assert "\\begin{foo-env}" in styler.to_latex(environment="foo-env")
459
+
460
+
461
+ def test_parse_latex_table_styles(styler):
462
+ styler.set_table_styles(
463
+ [
464
+ {"selector": "foo", "props": [("attr", "value")]},
465
+ {"selector": "bar", "props": [("attr", "overwritten")]},
466
+ {"selector": "bar", "props": [("attr", "baz"), ("attr2", "ignored")]},
467
+ {"selector": "label", "props": [("", "{figΒ§item}")]},
468
+ ]
469
+ )
470
+ assert _parse_latex_table_styles(styler.table_styles, "bar") == "baz"
471
+
472
+ # test 'Β§' replaced by ':' [for CSS compatibility]
473
+ assert _parse_latex_table_styles(styler.table_styles, "label") == "{fig:item}"
474
+
475
+
476
+ def test_parse_latex_cell_styles_basic(): # test nesting
477
+ cell_style = [("itshape", "--rwrap"), ("cellcolor", "[rgb]{0,1,1}--rwrap")]
478
+ expected = "\\itshape{\\cellcolor[rgb]{0,1,1}{text}}"
479
+ assert _parse_latex_cell_styles(cell_style, "text") == expected
480
+
481
+
482
+ @pytest.mark.parametrize(
483
+ "wrap_arg, expected",
484
+ [ # test wrapping
485
+ ("", "\\<command><options> <display_value>"),
486
+ ("--wrap", "{\\<command><options> <display_value>}"),
487
+ ("--nowrap", "\\<command><options> <display_value>"),
488
+ ("--lwrap", "{\\<command><options>} <display_value>"),
489
+ ("--dwrap", "{\\<command><options>}{<display_value>}"),
490
+ ("--rwrap", "\\<command><options>{<display_value>}"),
491
+ ],
492
+ )
493
+ def test_parse_latex_cell_styles_braces(wrap_arg, expected):
494
+ cell_style = [("<command>", f"<options>{wrap_arg}")]
495
+ assert _parse_latex_cell_styles(cell_style, "<display_value>") == expected
496
+
497
+
498
+ def test_parse_latex_header_span():
499
+ cell = {"attributes": 'colspan="3"', "display_value": "text", "cellstyle": []}
500
+ expected = "\\multicolumn{3}{Y}{text}"
501
+ assert _parse_latex_header_span(cell, "X", "Y") == expected
502
+
503
+ cell = {"attributes": 'rowspan="5"', "display_value": "text", "cellstyle": []}
504
+ expected = "\\multirow[X]{5}{*}{text}"
505
+ assert _parse_latex_header_span(cell, "X", "Y") == expected
506
+
507
+ cell = {"display_value": "text", "cellstyle": []}
508
+ assert _parse_latex_header_span(cell, "X", "Y") == "text"
509
+
510
+ cell = {"display_value": "text", "cellstyle": [("bfseries", "--rwrap")]}
511
+ assert _parse_latex_header_span(cell, "X", "Y") == "\\bfseries{text}"
512
+
513
+
514
+ def test_parse_latex_table_wrapping(styler):
515
+ styler.set_table_styles(
516
+ [
517
+ {"selector": "toprule", "props": ":value"},
518
+ {"selector": "bottomrule", "props": ":value"},
519
+ {"selector": "midrule", "props": ":value"},
520
+ {"selector": "column_format", "props": ":value"},
521
+ ]
522
+ )
523
+ assert _parse_latex_table_wrapping(styler.table_styles, styler.caption) is False
524
+ assert _parse_latex_table_wrapping(styler.table_styles, "some caption") is True
525
+ styler.set_table_styles(
526
+ [
527
+ {"selector": "not-ignored", "props": ":value"},
528
+ ],
529
+ overwrite=False,
530
+ )
531
+ assert _parse_latex_table_wrapping(styler.table_styles, None) is True
532
+
533
+
534
+ def test_short_caption(styler):
535
+ result = styler.to_latex(caption=("full cap", "short cap"))
536
+ assert "\\caption[short cap]{full cap}" in result
537
+
538
+
539
+ @pytest.mark.parametrize(
540
+ "css, expected",
541
+ [
542
+ ([("color", "red")], [("color", "{red}")]), # test color and input format types
543
+ (
544
+ [("color", "rgb(128, 128, 128 )")],
545
+ [("color", "[rgb]{0.502, 0.502, 0.502}")],
546
+ ),
547
+ (
548
+ [("color", "rgb(128, 50%, 25% )")],
549
+ [("color", "[rgb]{0.502, 0.500, 0.250}")],
550
+ ),
551
+ (
552
+ [("color", "rgba(128,128,128,1)")],
553
+ [("color", "[rgb]{0.502, 0.502, 0.502}")],
554
+ ),
555
+ ([("color", "#FF00FF")], [("color", "[HTML]{FF00FF}")]),
556
+ ([("color", "#F0F")], [("color", "[HTML]{FF00FF}")]),
557
+ ([("font-weight", "bold")], [("bfseries", "")]), # test font-weight and types
558
+ ([("font-weight", "bolder")], [("bfseries", "")]),
559
+ ([("font-weight", "normal")], []),
560
+ ([("background-color", "red")], [("cellcolor", "{red}--lwrap")]),
561
+ (
562
+ [("background-color", "#FF00FF")], # test background-color command and wrap
563
+ [("cellcolor", "[HTML]{FF00FF}--lwrap")],
564
+ ),
565
+ ([("font-style", "italic")], [("itshape", "")]), # test font-style and types
566
+ ([("font-style", "oblique")], [("slshape", "")]),
567
+ ([("font-style", "normal")], []),
568
+ ([("color", "red /*--dwrap*/")], [("color", "{red}--dwrap")]), # css comments
569
+ ([("background-color", "red /* --dwrap */")], [("cellcolor", "{red}--dwrap")]),
570
+ ],
571
+ )
572
+ def test_parse_latex_css_conversion(css, expected):
573
+ result = _parse_latex_css_conversion(css)
574
+ assert result == expected
575
+
576
+
577
+ @pytest.mark.parametrize(
578
+ "env, inner_env",
579
+ [
580
+ (None, "tabular"),
581
+ ("table", "tabular"),
582
+ ("longtable", "longtable"),
583
+ ],
584
+ )
585
+ @pytest.mark.parametrize(
586
+ "convert, exp", [(True, "bfseries"), (False, "font-weightbold")]
587
+ )
588
+ def test_parse_latex_css_convert_minimal(styler, env, inner_env, convert, exp):
589
+ # parameters ensure longtable template is also tested
590
+ styler.highlight_max(props="font-weight:bold;")
591
+ result = styler.to_latex(convert_css=convert, environment=env)
592
+ expected = dedent(
593
+ f"""\
594
+ 0 & 0 & \\{exp} -0.61 & ab \\\\
595
+ 1 & \\{exp} 1 & -1.22 & \\{exp} cd \\\\
596
+ \\end{{{inner_env}}}
597
+ """
598
+ )
599
+ assert expected in result
600
+
601
+
602
+ def test_parse_latex_css_conversion_option():
603
+ css = [("command", "option--latex--wrap")]
604
+ expected = [("command", "option--wrap")]
605
+ result = _parse_latex_css_conversion(css)
606
+ assert result == expected
607
+
608
+
609
+ def test_styler_object_after_render(styler):
610
+ # GH 42320
611
+ pre_render = styler._copy(deepcopy=True)
612
+ styler.to_latex(
613
+ column_format="rllr",
614
+ position="h",
615
+ position_float="centering",
616
+ hrules=True,
617
+ label="my lab",
618
+ caption="my cap",
619
+ )
620
+
621
+ assert pre_render.table_styles == styler.table_styles
622
+ assert pre_render.caption == styler.caption
623
+
624
+
625
+ def test_longtable_comprehensive(styler):
626
+ result = styler.to_latex(
627
+ environment="longtable", hrules=True, label="fig:A", caption=("full", "short")
628
+ )
629
+ expected = dedent(
630
+ """\
631
+ \\begin{longtable}{lrrl}
632
+ \\caption[short]{full} \\label{fig:A} \\\\
633
+ \\toprule
634
+ & A & B & C \\\\
635
+ \\midrule
636
+ \\endfirsthead
637
+ \\caption[]{full} \\\\
638
+ \\toprule
639
+ & A & B & C \\\\
640
+ \\midrule
641
+ \\endhead
642
+ \\midrule
643
+ \\multicolumn{4}{r}{Continued on next page} \\\\
644
+ \\midrule
645
+ \\endfoot
646
+ \\bottomrule
647
+ \\endlastfoot
648
+ 0 & 0 & -0.61 & ab \\\\
649
+ 1 & 1 & -1.22 & cd \\\\
650
+ \\end{longtable}
651
+ """
652
+ )
653
+ assert result == expected
654
+
655
+
656
+ def test_longtable_minimal(styler):
657
+ result = styler.to_latex(environment="longtable")
658
+ expected = dedent(
659
+ """\
660
+ \\begin{longtable}{lrrl}
661
+ & A & B & C \\\\
662
+ \\endfirsthead
663
+ & A & B & C \\\\
664
+ \\endhead
665
+ \\multicolumn{4}{r}{Continued on next page} \\\\
666
+ \\endfoot
667
+ \\endlastfoot
668
+ 0 & 0 & -0.61 & ab \\\\
669
+ 1 & 1 & -1.22 & cd \\\\
670
+ \\end{longtable}
671
+ """
672
+ )
673
+ assert result == expected
674
+
675
+
676
+ @pytest.mark.parametrize(
677
+ "sparse, exp, siunitx",
678
+ [
679
+ (True, "{} & \\multicolumn{2}{r}{A} & {B}", True),
680
+ (False, "{} & {A} & {A} & {B}", True),
681
+ (True, " & \\multicolumn{2}{r}{A} & B", False),
682
+ (False, " & A & A & B", False),
683
+ ],
684
+ )
685
+ def test_longtable_multiindex_columns(df, sparse, exp, siunitx):
686
+ cidx = MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("B", "c")])
687
+ df.columns = cidx
688
+ with_si = "{} & {a} & {b} & {c} \\\\"
689
+ without_si = " & a & b & c \\\\"
690
+ expected = dedent(
691
+ f"""\
692
+ \\begin{{longtable}}{{l{"SS" if siunitx else "rr"}l}}
693
+ {exp} \\\\
694
+ {with_si if siunitx else without_si}
695
+ \\endfirsthead
696
+ {exp} \\\\
697
+ {with_si if siunitx else without_si}
698
+ \\endhead
699
+ """
700
+ )
701
+ result = df.style.to_latex(
702
+ environment="longtable", sparse_columns=sparse, siunitx=siunitx
703
+ )
704
+ assert expected in result
705
+
706
+
707
+ @pytest.mark.parametrize(
708
+ "caption, cap_exp",
709
+ [
710
+ ("full", ("{full}", "")),
711
+ (("full", "short"), ("{full}", "[short]")),
712
+ ],
713
+ )
714
+ @pytest.mark.parametrize("label, lab_exp", [(None, ""), ("tab:A", " \\label{tab:A}")])
715
+ def test_longtable_caption_label(styler, caption, cap_exp, label, lab_exp):
716
+ cap_exp1 = f"\\caption{cap_exp[1]}{cap_exp[0]}"
717
+ cap_exp2 = f"\\caption[]{cap_exp[0]}"
718
+
719
+ expected = dedent(
720
+ f"""\
721
+ {cap_exp1}{lab_exp} \\\\
722
+ & A & B & C \\\\
723
+ \\endfirsthead
724
+ {cap_exp2} \\\\
725
+ """
726
+ )
727
+ assert expected in styler.to_latex(
728
+ environment="longtable", caption=caption, label=label
729
+ )
730
+
731
+
732
+ @pytest.mark.parametrize("index", [True, False])
733
+ @pytest.mark.parametrize(
734
+ "columns, siunitx",
735
+ [
736
+ (True, True),
737
+ (True, False),
738
+ (False, False),
739
+ ],
740
+ )
741
+ def test_apply_map_header_render_mi(df_ext, index, columns, siunitx):
742
+ cidx = MultiIndex.from_tuples([("Z", "a"), ("Z", "b"), ("Y", "c")])
743
+ ridx = MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("B", "c")])
744
+ df_ext.index, df_ext.columns = ridx, cidx
745
+ styler = df_ext.style
746
+
747
+ func = lambda v: "bfseries: --rwrap" if "A" in v or "Z" in v or "c" in v else None
748
+
749
+ if index:
750
+ styler.map_index(func, axis="index")
751
+ if columns:
752
+ styler.map_index(func, axis="columns")
753
+
754
+ result = styler.to_latex(siunitx=siunitx)
755
+
756
+ expected_index = dedent(
757
+ """\
758
+ \\multirow[c]{2}{*}{\\bfseries{A}} & a & 0 & -0.610000 & ab \\\\
759
+ \\bfseries{} & b & 1 & -1.220000 & cd \\\\
760
+ B & \\bfseries{c} & 2 & -2.220000 & de \\\\
761
+ """
762
+ )
763
+ assert (expected_index in result) is index
764
+
765
+ exp_cols_si = dedent(
766
+ """\
767
+ {} & {} & \\multicolumn{2}{r}{\\bfseries{Z}} & {Y} \\\\
768
+ {} & {} & {a} & {b} & {\\bfseries{c}} \\\\
769
+ """
770
+ )
771
+ exp_cols_no_si = """\
772
+ & & \\multicolumn{2}{r}{\\bfseries{Z}} & Y \\\\
773
+ & & a & b & \\bfseries{c} \\\\
774
+ """
775
+ assert ((exp_cols_si if siunitx else exp_cols_no_si) in result) is columns
776
+
777
+
778
+ def test_repr_option(styler):
779
+ assert "<style" in styler._repr_html_()[:6]
780
+ assert styler._repr_latex_() is None
781
+ with option_context("styler.render.repr", "latex"):
782
+ assert "\\begin{tabular}" in styler._repr_latex_()[:15]
783
+ assert styler._repr_html_() is None
784
+
785
+
786
+ @pytest.mark.parametrize("option", ["hrules"])
787
+ def test_bool_options(styler, option):
788
+ with option_context(f"styler.latex.{option}", False):
789
+ latex_false = styler.to_latex()
790
+ with option_context(f"styler.latex.{option}", True):
791
+ latex_true = styler.to_latex()
792
+ assert latex_false != latex_true # options are reactive under to_latex(*no_args)
793
+
794
+
795
+ def test_siunitx_basic_headers(styler):
796
+ assert "{} & {A} & {B} & {C} \\\\" in styler.to_latex(siunitx=True)
797
+ assert " & A & B & C \\\\" in styler.to_latex() # default siunitx=False
798
+
799
+
800
+ @pytest.mark.parametrize("axis", ["index", "columns"])
801
+ def test_css_convert_apply_index(styler, axis):
802
+ styler.map_index(lambda x: "font-weight: bold;", axis=axis)
803
+ for label in getattr(styler, axis):
804
+ assert f"\\bfseries {label}" in styler.to_latex(convert_css=True)
805
+
806
+
807
+ def test_hide_index_latex(styler):
808
+ # GH 43637
809
+ styler.hide([0], axis=0)
810
+ result = styler.to_latex()
811
+ expected = dedent(
812
+ """\
813
+ \\begin{tabular}{lrrl}
814
+ & A & B & C \\\\
815
+ 1 & 1 & -1.22 & cd \\\\
816
+ \\end{tabular}
817
+ """
818
+ )
819
+ assert expected == result
820
+
821
+
822
+ def test_latex_hiding_index_columns_multiindex_alignment():
823
+ # gh 43644
824
+ midx = MultiIndex.from_product(
825
+ [["i0", "j0"], ["i1"], ["i2", "j2"]], names=["i-0", "i-1", "i-2"]
826
+ )
827
+ cidx = MultiIndex.from_product(
828
+ [["c0"], ["c1", "d1"], ["c2", "d2"]], names=["c-0", "c-1", "c-2"]
829
+ )
830
+ df = DataFrame(np.arange(16).reshape(4, 4), index=midx, columns=cidx)
831
+ styler = Styler(df, uuid_len=0)
832
+ styler.hide(level=1, axis=0).hide(level=0, axis=1)
833
+ styler.hide([("i0", "i1", "i2")], axis=0)
834
+ styler.hide([("c0", "c1", "c2")], axis=1)
835
+ styler.map(lambda x: "color:{red};" if x == 5 else "")
836
+ styler.map_index(lambda x: "color:{blue};" if "j" in x else "")
837
+ result = styler.to_latex()
838
+ expected = dedent(
839
+ """\
840
+ \\begin{tabular}{llrrr}
841
+ & c-1 & c1 & \\multicolumn{2}{r}{d1} \\\\
842
+ & c-2 & d2 & c2 & d2 \\\\
843
+ i-0 & i-2 & & & \\\\
844
+ i0 & \\color{blue} j2 & \\color{red} 5 & 6 & 7 \\\\
845
+ \\multirow[c]{2}{*}{\\color{blue} j0} & i2 & 9 & 10 & 11 \\\\
846
+ \\color{blue} & \\color{blue} j2 & 13 & 14 & 15 \\\\
847
+ \\end{tabular}
848
+ """
849
+ )
850
+ assert result == expected
851
+
852
+
853
+ def test_rendered_links():
854
+ # note the majority of testing is done in test_html.py: test_rendered_links
855
+ # these test only the alternative latex format is functional
856
+ df = DataFrame(["text www.domain.com text"])
857
+ result = df.style.format(hyperlinks="latex").to_latex()
858
+ assert r"text \href{www.domain.com}{www.domain.com} text" in result
859
+
860
+
861
+ def test_apply_index_hidden_levels():
862
+ # gh 45156
863
+ styler = DataFrame(
864
+ [[1]],
865
+ index=MultiIndex.from_tuples([(0, 1)], names=["l0", "l1"]),
866
+ columns=MultiIndex.from_tuples([(0, 1)], names=["c0", "c1"]),
867
+ ).style
868
+ styler.hide(level=1)
869
+ styler.map_index(lambda v: "color: red;", level=0, axis=1)
870
+ result = styler.to_latex(convert_css=True)
871
+ expected = dedent(
872
+ """\
873
+ \\begin{tabular}{lr}
874
+ c0 & \\color{red} 0 \\\\
875
+ c1 & 1 \\\\
876
+ l0 & \\\\
877
+ 0 & 1 \\\\
878
+ \\end{tabular}
879
+ """
880
+ )
881
+ assert result == expected
882
+
883
+
884
+ @pytest.mark.parametrize("clines", ["bad", "index", "skip-last", "all", "data"])
885
+ def test_clines_validation(clines, styler):
886
+ msg = f"`clines` value of {clines} is invalid."
887
+ with pytest.raises(ValueError, match=msg):
888
+ styler.to_latex(clines=clines)
889
+
890
+
891
+ @pytest.mark.parametrize(
892
+ "clines, exp",
893
+ [
894
+ ("all;index", "\n\\cline{1-1}"),
895
+ ("all;data", "\n\\cline{1-2}"),
896
+ ("skip-last;index", ""),
897
+ ("skip-last;data", ""),
898
+ (None, ""),
899
+ ],
900
+ )
901
+ @pytest.mark.parametrize("env", ["table", "longtable"])
902
+ def test_clines_index(clines, exp, env):
903
+ df = DataFrame([[1], [2], [3], [4]])
904
+ result = df.style.to_latex(clines=clines, environment=env)
905
+ expected = f"""\
906
+ 0 & 1 \\\\{exp}
907
+ 1 & 2 \\\\{exp}
908
+ 2 & 3 \\\\{exp}
909
+ 3 & 4 \\\\{exp}
910
+ """
911
+ assert expected in result
912
+
913
+
914
+ @pytest.mark.parametrize(
915
+ "clines, expected",
916
+ [
917
+ (
918
+ None,
919
+ dedent(
920
+ """\
921
+ \\multirow[c]{2}{*}{A} & X & 1 \\\\
922
+ & Y & 2 \\\\
923
+ \\multirow[c]{2}{*}{B} & X & 3 \\\\
924
+ & Y & 4 \\\\
925
+ """
926
+ ),
927
+ ),
928
+ (
929
+ "skip-last;index",
930
+ dedent(
931
+ """\
932
+ \\multirow[c]{2}{*}{A} & X & 1 \\\\
933
+ & Y & 2 \\\\
934
+ \\cline{1-2}
935
+ \\multirow[c]{2}{*}{B} & X & 3 \\\\
936
+ & Y & 4 \\\\
937
+ \\cline{1-2}
938
+ """
939
+ ),
940
+ ),
941
+ (
942
+ "skip-last;data",
943
+ dedent(
944
+ """\
945
+ \\multirow[c]{2}{*}{A} & X & 1 \\\\
946
+ & Y & 2 \\\\
947
+ \\cline{1-3}
948
+ \\multirow[c]{2}{*}{B} & X & 3 \\\\
949
+ & Y & 4 \\\\
950
+ \\cline{1-3}
951
+ """
952
+ ),
953
+ ),
954
+ (
955
+ "all;index",
956
+ dedent(
957
+ """\
958
+ \\multirow[c]{2}{*}{A} & X & 1 \\\\
959
+ \\cline{2-2}
960
+ & Y & 2 \\\\
961
+ \\cline{1-2} \\cline{2-2}
962
+ \\multirow[c]{2}{*}{B} & X & 3 \\\\
963
+ \\cline{2-2}
964
+ & Y & 4 \\\\
965
+ \\cline{1-2} \\cline{2-2}
966
+ """
967
+ ),
968
+ ),
969
+ (
970
+ "all;data",
971
+ dedent(
972
+ """\
973
+ \\multirow[c]{2}{*}{A} & X & 1 \\\\
974
+ \\cline{2-3}
975
+ & Y & 2 \\\\
976
+ \\cline{1-3} \\cline{2-3}
977
+ \\multirow[c]{2}{*}{B} & X & 3 \\\\
978
+ \\cline{2-3}
979
+ & Y & 4 \\\\
980
+ \\cline{1-3} \\cline{2-3}
981
+ """
982
+ ),
983
+ ),
984
+ ],
985
+ )
986
+ @pytest.mark.parametrize("env", ["table"])
987
+ def test_clines_multiindex(clines, expected, env):
988
+ # also tests simultaneously with hidden rows and a hidden multiindex level
989
+ midx = MultiIndex.from_product([["A", "-", "B"], [0], ["X", "Y"]])
990
+ df = DataFrame([[1], [2], [99], [99], [3], [4]], index=midx)
991
+ styler = df.style
992
+ styler.hide([("-", 0, "X"), ("-", 0, "Y")])
993
+ styler.hide(level=1)
994
+ result = styler.to_latex(clines=clines, environment=env)
995
+ assert expected in result
996
+
997
+
998
+ def test_col_format_len(styler):
999
+ # gh 46037
1000
+ result = styler.to_latex(environment="longtable", column_format="lrr{10cm}")
1001
+ expected = r"\multicolumn{4}{r}{Continued on next page} \\"
1002
+ assert expected in result
1003
+
1004
+
1005
+ def test_concat(styler):
1006
+ result = styler.concat(styler.data.agg(["sum"]).style).to_latex()
1007
+ expected = dedent(
1008
+ """\
1009
+ \\begin{tabular}{lrrl}
1010
+ & A & B & C \\\\
1011
+ 0 & 0 & -0.61 & ab \\\\
1012
+ 1 & 1 & -1.22 & cd \\\\
1013
+ sum & 1 & -1.830000 & abcd \\\\
1014
+ \\end{tabular}
1015
+ """
1016
+ )
1017
+ assert result == expected
1018
+
1019
+
1020
+ def test_concat_recursion():
1021
+ # tests hidden row recursion and applied styles
1022
+ styler1 = DataFrame([[1], [9]]).style.hide([1]).highlight_min(color="red")
1023
+ styler2 = DataFrame([[9], [2]]).style.hide([0]).highlight_min(color="green")
1024
+ styler3 = DataFrame([[3], [9]]).style.hide([1]).highlight_min(color="blue")
1025
+
1026
+ result = styler1.concat(styler2.concat(styler3)).to_latex(convert_css=True)
1027
+ expected = dedent(
1028
+ """\
1029
+ \\begin{tabular}{lr}
1030
+ & 0 \\\\
1031
+ 0 & {\\cellcolor{red}} 1 \\\\
1032
+ 1 & {\\cellcolor{green}} 2 \\\\
1033
+ 0 & {\\cellcolor{blue}} 3 \\\\
1034
+ \\end{tabular}
1035
+ """
1036
+ )
1037
+ assert result == expected
1038
+
1039
+
1040
+ def test_concat_chain():
1041
+ # tests hidden row recursion and applied styles
1042
+ styler1 = DataFrame([[1], [9]]).style.hide([1]).highlight_min(color="red")
1043
+ styler2 = DataFrame([[9], [2]]).style.hide([0]).highlight_min(color="green")
1044
+ styler3 = DataFrame([[3], [9]]).style.hide([1]).highlight_min(color="blue")
1045
+
1046
+ result = styler1.concat(styler2).concat(styler3).to_latex(convert_css=True)
1047
+ expected = dedent(
1048
+ """\
1049
+ \\begin{tabular}{lr}
1050
+ & 0 \\\\
1051
+ 0 & {\\cellcolor{red}} 1 \\\\
1052
+ 1 & {\\cellcolor{green}} 2 \\\\
1053
+ 0 & {\\cellcolor{blue}} 3 \\\\
1054
+ \\end{tabular}
1055
+ """
1056
+ )
1057
+ assert result == expected
1058
+
1059
+
1060
+ @pytest.mark.parametrize(
1061
+ "df, expected",
1062
+ [
1063
+ (
1064
+ DataFrame(),
1065
+ dedent(
1066
+ """\
1067
+ \\begin{tabular}{l}
1068
+ \\end{tabular}
1069
+ """
1070
+ ),
1071
+ ),
1072
+ (
1073
+ DataFrame(columns=["a", "b", "c"]),
1074
+ dedent(
1075
+ """\
1076
+ \\begin{tabular}{llll}
1077
+ & a & b & c \\\\
1078
+ \\end{tabular}
1079
+ """
1080
+ ),
1081
+ ),
1082
+ ],
1083
+ )
1084
+ @pytest.mark.parametrize(
1085
+ "clines", [None, "all;data", "all;index", "skip-last;data", "skip-last;index"]
1086
+ )
1087
+ def test_empty_clines(df: DataFrame, expected: str, clines: str):
1088
+ # GH 47203
1089
+ result = df.style.to_latex(clines=clines)
1090
+ assert result == expected
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/test_to_string.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from textwrap import dedent
2
+
3
+ import pytest
4
+
5
+ from pandas import (
6
+ DataFrame,
7
+ Series,
8
+ )
9
+
10
+ pytest.importorskip("jinja2")
11
+ from pandas.io.formats.style import Styler
12
+
13
+
14
+ @pytest.fixture
15
+ def df():
16
+ return DataFrame(
17
+ {"A": [0, 1], "B": [-0.61, -1.22], "C": Series(["ab", "cd"], dtype=object)}
18
+ )
19
+
20
+
21
+ @pytest.fixture
22
+ def styler(df):
23
+ return Styler(df, uuid_len=0, precision=2)
24
+
25
+
26
+ def test_basic_string(styler):
27
+ result = styler.to_string()
28
+ expected = dedent(
29
+ """\
30
+ A B C
31
+ 0 0 -0.61 ab
32
+ 1 1 -1.22 cd
33
+ """
34
+ )
35
+ assert result == expected
36
+
37
+
38
+ def test_string_delimiter(styler):
39
+ result = styler.to_string(delimiter=";")
40
+ expected = dedent(
41
+ """\
42
+ ;A;B;C
43
+ 0;0;-0.61;ab
44
+ 1;1;-1.22;cd
45
+ """
46
+ )
47
+ assert result == expected
48
+
49
+
50
+ def test_concat(styler):
51
+ result = styler.concat(styler.data.agg(["sum"]).style).to_string()
52
+ expected = dedent(
53
+ """\
54
+ A B C
55
+ 0 0 -0.61 ab
56
+ 1 1 -1.22 cd
57
+ sum 1 -1.830000 abcd
58
+ """
59
+ )
60
+ assert result == expected
61
+
62
+
63
+ def test_concat_recursion(styler):
64
+ df = styler.data
65
+ styler1 = styler
66
+ styler2 = Styler(df.agg(["sum"]), uuid_len=0, precision=3)
67
+ styler3 = Styler(df.agg(["sum"]), uuid_len=0, precision=4)
68
+ result = styler1.concat(styler2.concat(styler3)).to_string()
69
+ expected = dedent(
70
+ """\
71
+ A B C
72
+ 0 0 -0.61 ab
73
+ 1 1 -1.22 cd
74
+ sum 1 -1.830 abcd
75
+ sum 1 -1.8300 abcd
76
+ """
77
+ )
78
+ assert result == expected
79
+
80
+
81
+ def test_concat_chain(styler):
82
+ df = styler.data
83
+ styler1 = styler
84
+ styler2 = Styler(df.agg(["sum"]), uuid_len=0, precision=3)
85
+ styler3 = Styler(df.agg(["sum"]), uuid_len=0, precision=4)
86
+ result = styler1.concat(styler2).concat(styler3).to_string()
87
+ expected = dedent(
88
+ """\
89
+ A B C
90
+ 0 0 -0.61 ab
91
+ 1 1 -1.22 cd
92
+ sum 1 -1.830 abcd
93
+ sum 1 -1.8300 abcd
94
+ """
95
+ )
96
+ assert result == expected
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/style/test_tooltip.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas import DataFrame
5
+
6
+ pytest.importorskip("jinja2")
7
+ from pandas.io.formats.style import Styler
8
+
9
+
10
+ @pytest.fixture
11
+ def df():
12
+ return DataFrame(
13
+ data=[[0, 1, 2], [3, 4, 5], [6, 7, 8]],
14
+ columns=["A", "B", "C"],
15
+ index=["x", "y", "z"],
16
+ )
17
+
18
+
19
+ @pytest.fixture
20
+ def styler(df):
21
+ return Styler(df, uuid_len=0)
22
+
23
+
24
+ @pytest.mark.parametrize(
25
+ "ttips",
26
+ [
27
+ DataFrame( # Test basic reindex and ignoring blank
28
+ data=[["Min", "Max"], [np.nan, ""]],
29
+ columns=["A", "C"],
30
+ index=["x", "y"],
31
+ ),
32
+ DataFrame( # Test non-referenced columns, reversed col names, short index
33
+ data=[["Max", "Min", "Bad-Col"]], columns=["C", "A", "D"], index=["x"]
34
+ ),
35
+ ],
36
+ )
37
+ def test_tooltip_render(ttips, styler):
38
+ # GH 21266
39
+ result = styler.set_tooltips(ttips).to_html()
40
+
41
+ # test tooltip table level class
42
+ assert "#T_ .pd-t {\n visibility: hidden;\n" in result
43
+
44
+ # test 'Min' tooltip added
45
+ assert "#T_ #T__row0_col0:hover .pd-t {\n visibility: visible;\n}" in result
46
+ assert '#T_ #T__row0_col0 .pd-t::after {\n content: "Min";\n}' in result
47
+ assert 'class="data row0 col0" >0<span class="pd-t"></span></td>' in result
48
+
49
+ # test 'Max' tooltip added
50
+ assert "#T_ #T__row0_col2:hover .pd-t {\n visibility: visible;\n}" in result
51
+ assert '#T_ #T__row0_col2 .pd-t::after {\n content: "Max";\n}' in result
52
+ assert 'class="data row0 col2" >2<span class="pd-t"></span></td>' in result
53
+
54
+ # test Nan, empty string and bad column ignored
55
+ assert "#T_ #T__row1_col0:hover .pd-t {\n visibility: visible;\n}" not in result
56
+ assert "#T_ #T__row1_col1:hover .pd-t {\n visibility: visible;\n}" not in result
57
+ assert "#T_ #T__row0_col1:hover .pd-t {\n visibility: visible;\n}" not in result
58
+ assert "#T_ #T__row1_col2:hover .pd-t {\n visibility: visible;\n}" not in result
59
+ assert "Bad-Col" not in result
60
+
61
+
62
+ def test_tooltip_ignored(styler):
63
+ # GH 21266
64
+ result = styler.to_html() # no set_tooltips() creates no <span>
65
+ assert '<style type="text/css">\n</style>' in result
66
+ assert '<span class="pd-t"></span>' not in result
67
+
68
+
69
+ def test_tooltip_css_class(styler):
70
+ # GH 21266
71
+ result = styler.set_tooltips(
72
+ DataFrame([["tooltip"]], index=["x"], columns=["A"]),
73
+ css_class="other-class",
74
+ props=[("color", "green")],
75
+ ).to_html()
76
+ assert "#T_ .other-class {\n color: green;\n" in result
77
+ assert '#T_ #T__row0_col0 .other-class::after {\n content: "tooltip";\n' in result
78
+
79
+ # GH 39563
80
+ result = styler.set_tooltips( # set_tooltips overwrites previous
81
+ DataFrame([["tooltip"]], index=["x"], columns=["A"]),
82
+ css_class="another-class",
83
+ props="color:green;color:red;",
84
+ ).to_html()
85
+ assert "#T_ .another-class {\n color: green;\n color: red;\n}" in result
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/test_console.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import locale
2
+
3
+ import pytest
4
+
5
+ from pandas._config import detect_console_encoding
6
+
7
+
8
+ class MockEncoding:
9
+ """
10
+ Used to add a side effect when accessing the 'encoding' property. If the
11
+ side effect is a str in nature, the value will be returned. Otherwise, the
12
+ side effect should be an exception that will be raised.
13
+ """
14
+
15
+ def __init__(self, encoding) -> None:
16
+ super().__init__()
17
+ self.val = encoding
18
+
19
+ @property
20
+ def encoding(self):
21
+ return self.raise_or_return(self.val)
22
+
23
+ @staticmethod
24
+ def raise_or_return(val):
25
+ if isinstance(val, str):
26
+ return val
27
+ else:
28
+ raise val
29
+
30
+
31
+ @pytest.mark.parametrize("empty,filled", [["stdin", "stdout"], ["stdout", "stdin"]])
32
+ def test_detect_console_encoding_from_stdout_stdin(monkeypatch, empty, filled):
33
+ # Ensures that when sys.stdout.encoding or sys.stdin.encoding is used when
34
+ # they have values filled.
35
+ # GH 21552
36
+ with monkeypatch.context() as context:
37
+ context.setattr(f"sys.{empty}", MockEncoding(""))
38
+ context.setattr(f"sys.{filled}", MockEncoding(filled))
39
+ assert detect_console_encoding() == filled
40
+
41
+
42
+ @pytest.mark.parametrize("encoding", [AttributeError, OSError, "ascii"])
43
+ def test_detect_console_encoding_fallback_to_locale(monkeypatch, encoding):
44
+ # GH 21552
45
+ with monkeypatch.context() as context:
46
+ context.setattr("locale.getpreferredencoding", lambda: "foo")
47
+ context.setattr("sys.stdout", MockEncoding(encoding))
48
+ assert detect_console_encoding() == "foo"
49
+
50
+
51
+ @pytest.mark.parametrize(
52
+ "std,locale",
53
+ [
54
+ ["ascii", "ascii"],
55
+ ["ascii", locale.Error],
56
+ [AttributeError, "ascii"],
57
+ [AttributeError, locale.Error],
58
+ [OSError, "ascii"],
59
+ [OSError, locale.Error],
60
+ ],
61
+ )
62
+ def test_detect_console_encoding_fallback_to_default(monkeypatch, std, locale):
63
+ # When both the stdout/stdin encoding and locale preferred encoding checks
64
+ # fail (or return 'ascii', we should default to the sys default encoding.
65
+ # GH 21552
66
+ with monkeypatch.context() as context:
67
+ context.setattr(
68
+ "locale.getpreferredencoding", lambda: MockEncoding.raise_or_return(locale)
69
+ )
70
+ context.setattr("sys.stdout", MockEncoding(std))
71
+ context.setattr("sys.getdefaultencoding", lambda: "sysDefaultEncoding")
72
+ assert detect_console_encoding() == "sysDefaultEncoding"
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/test_eng_formatting.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas import (
5
+ DataFrame,
6
+ reset_option,
7
+ set_eng_float_format,
8
+ )
9
+
10
+ from pandas.io.formats.format import EngFormatter
11
+
12
+
13
+ @pytest.fixture(autouse=True)
14
+ def reset_float_format():
15
+ yield
16
+ reset_option("display.float_format")
17
+
18
+
19
+ class TestEngFormatter:
20
+ def test_eng_float_formatter2(self, float_frame):
21
+ df = float_frame
22
+ df.loc[5] = 0
23
+
24
+ set_eng_float_format()
25
+ repr(df)
26
+
27
+ set_eng_float_format(use_eng_prefix=True)
28
+ repr(df)
29
+
30
+ set_eng_float_format(accuracy=0)
31
+ repr(df)
32
+
33
+ def test_eng_float_formatter(self):
34
+ df = DataFrame({"A": [1.41, 141.0, 14100, 1410000.0]})
35
+
36
+ set_eng_float_format()
37
+ result = df.to_string()
38
+ expected = (
39
+ " A\n"
40
+ "0 1.410E+00\n"
41
+ "1 141.000E+00\n"
42
+ "2 14.100E+03\n"
43
+ "3 1.410E+06"
44
+ )
45
+ assert result == expected
46
+
47
+ set_eng_float_format(use_eng_prefix=True)
48
+ result = df.to_string()
49
+ expected = " A\n0 1.410\n1 141.000\n2 14.100k\n3 1.410M"
50
+ assert result == expected
51
+
52
+ set_eng_float_format(accuracy=0)
53
+ result = df.to_string()
54
+ expected = " A\n0 1E+00\n1 141E+00\n2 14E+03\n3 1E+06"
55
+ assert result == expected
56
+
57
+ def compare(self, formatter, input, output):
58
+ formatted_input = formatter(input)
59
+ assert formatted_input == output
60
+
61
+ def compare_all(self, formatter, in_out):
62
+ """
63
+ Parameters:
64
+ -----------
65
+ formatter: EngFormatter under test
66
+ in_out: list of tuples. Each tuple = (number, expected_formatting)
67
+
68
+ It is tested if 'formatter(number) == expected_formatting'.
69
+ *number* should be >= 0 because formatter(-number) == fmt is also
70
+ tested. *fmt* is derived from *expected_formatting*
71
+ """
72
+ for input, output in in_out:
73
+ self.compare(formatter, input, output)
74
+ self.compare(formatter, -input, "-" + output[1:])
75
+
76
+ def test_exponents_with_eng_prefix(self):
77
+ formatter = EngFormatter(accuracy=3, use_eng_prefix=True)
78
+ f = np.sqrt(2)
79
+ in_out = [
80
+ (f * 10**-24, " 1.414y"),
81
+ (f * 10**-23, " 14.142y"),
82
+ (f * 10**-22, " 141.421y"),
83
+ (f * 10**-21, " 1.414z"),
84
+ (f * 10**-20, " 14.142z"),
85
+ (f * 10**-19, " 141.421z"),
86
+ (f * 10**-18, " 1.414a"),
87
+ (f * 10**-17, " 14.142a"),
88
+ (f * 10**-16, " 141.421a"),
89
+ (f * 10**-15, " 1.414f"),
90
+ (f * 10**-14, " 14.142f"),
91
+ (f * 10**-13, " 141.421f"),
92
+ (f * 10**-12, " 1.414p"),
93
+ (f * 10**-11, " 14.142p"),
94
+ (f * 10**-10, " 141.421p"),
95
+ (f * 10**-9, " 1.414n"),
96
+ (f * 10**-8, " 14.142n"),
97
+ (f * 10**-7, " 141.421n"),
98
+ (f * 10**-6, " 1.414u"),
99
+ (f * 10**-5, " 14.142u"),
100
+ (f * 10**-4, " 141.421u"),
101
+ (f * 10**-3, " 1.414m"),
102
+ (f * 10**-2, " 14.142m"),
103
+ (f * 10**-1, " 141.421m"),
104
+ (f * 10**0, " 1.414"),
105
+ (f * 10**1, " 14.142"),
106
+ (f * 10**2, " 141.421"),
107
+ (f * 10**3, " 1.414k"),
108
+ (f * 10**4, " 14.142k"),
109
+ (f * 10**5, " 141.421k"),
110
+ (f * 10**6, " 1.414M"),
111
+ (f * 10**7, " 14.142M"),
112
+ (f * 10**8, " 141.421M"),
113
+ (f * 10**9, " 1.414G"),
114
+ (f * 10**10, " 14.142G"),
115
+ (f * 10**11, " 141.421G"),
116
+ (f * 10**12, " 1.414T"),
117
+ (f * 10**13, " 14.142T"),
118
+ (f * 10**14, " 141.421T"),
119
+ (f * 10**15, " 1.414P"),
120
+ (f * 10**16, " 14.142P"),
121
+ (f * 10**17, " 141.421P"),
122
+ (f * 10**18, " 1.414E"),
123
+ (f * 10**19, " 14.142E"),
124
+ (f * 10**20, " 141.421E"),
125
+ (f * 10**21, " 1.414Z"),
126
+ (f * 10**22, " 14.142Z"),
127
+ (f * 10**23, " 141.421Z"),
128
+ (f * 10**24, " 1.414Y"),
129
+ (f * 10**25, " 14.142Y"),
130
+ (f * 10**26, " 141.421Y"),
131
+ ]
132
+ self.compare_all(formatter, in_out)
133
+
134
+ def test_exponents_without_eng_prefix(self):
135
+ formatter = EngFormatter(accuracy=4, use_eng_prefix=False)
136
+ f = np.pi
137
+ in_out = [
138
+ (f * 10**-24, " 3.1416E-24"),
139
+ (f * 10**-23, " 31.4159E-24"),
140
+ (f * 10**-22, " 314.1593E-24"),
141
+ (f * 10**-21, " 3.1416E-21"),
142
+ (f * 10**-20, " 31.4159E-21"),
143
+ (f * 10**-19, " 314.1593E-21"),
144
+ (f * 10**-18, " 3.1416E-18"),
145
+ (f * 10**-17, " 31.4159E-18"),
146
+ (f * 10**-16, " 314.1593E-18"),
147
+ (f * 10**-15, " 3.1416E-15"),
148
+ (f * 10**-14, " 31.4159E-15"),
149
+ (f * 10**-13, " 314.1593E-15"),
150
+ (f * 10**-12, " 3.1416E-12"),
151
+ (f * 10**-11, " 31.4159E-12"),
152
+ (f * 10**-10, " 314.1593E-12"),
153
+ (f * 10**-9, " 3.1416E-09"),
154
+ (f * 10**-8, " 31.4159E-09"),
155
+ (f * 10**-7, " 314.1593E-09"),
156
+ (f * 10**-6, " 3.1416E-06"),
157
+ (f * 10**-5, " 31.4159E-06"),
158
+ (f * 10**-4, " 314.1593E-06"),
159
+ (f * 10**-3, " 3.1416E-03"),
160
+ (f * 10**-2, " 31.4159E-03"),
161
+ (f * 10**-1, " 314.1593E-03"),
162
+ (f * 10**0, " 3.1416E+00"),
163
+ (f * 10**1, " 31.4159E+00"),
164
+ (f * 10**2, " 314.1593E+00"),
165
+ (f * 10**3, " 3.1416E+03"),
166
+ (f * 10**4, " 31.4159E+03"),
167
+ (f * 10**5, " 314.1593E+03"),
168
+ (f * 10**6, " 3.1416E+06"),
169
+ (f * 10**7, " 31.4159E+06"),
170
+ (f * 10**8, " 314.1593E+06"),
171
+ (f * 10**9, " 3.1416E+09"),
172
+ (f * 10**10, " 31.4159E+09"),
173
+ (f * 10**11, " 314.1593E+09"),
174
+ (f * 10**12, " 3.1416E+12"),
175
+ (f * 10**13, " 31.4159E+12"),
176
+ (f * 10**14, " 314.1593E+12"),
177
+ (f * 10**15, " 3.1416E+15"),
178
+ (f * 10**16, " 31.4159E+15"),
179
+ (f * 10**17, " 314.1593E+15"),
180
+ (f * 10**18, " 3.1416E+18"),
181
+ (f * 10**19, " 31.4159E+18"),
182
+ (f * 10**20, " 314.1593E+18"),
183
+ (f * 10**21, " 3.1416E+21"),
184
+ (f * 10**22, " 31.4159E+21"),
185
+ (f * 10**23, " 314.1593E+21"),
186
+ (f * 10**24, " 3.1416E+24"),
187
+ (f * 10**25, " 31.4159E+24"),
188
+ (f * 10**26, " 314.1593E+24"),
189
+ ]
190
+ self.compare_all(formatter, in_out)
191
+
192
+ def test_rounding(self):
193
+ formatter = EngFormatter(accuracy=3, use_eng_prefix=True)
194
+ in_out = [
195
+ (5.55555, " 5.556"),
196
+ (55.5555, " 55.556"),
197
+ (555.555, " 555.555"),
198
+ (5555.55, " 5.556k"),
199
+ (55555.5, " 55.556k"),
200
+ (555555, " 555.555k"),
201
+ ]
202
+ self.compare_all(formatter, in_out)
203
+
204
+ formatter = EngFormatter(accuracy=1, use_eng_prefix=True)
205
+ in_out = [
206
+ (5.55555, " 5.6"),
207
+ (55.5555, " 55.6"),
208
+ (555.555, " 555.6"),
209
+ (5555.55, " 5.6k"),
210
+ (55555.5, " 55.6k"),
211
+ (555555, " 555.6k"),
212
+ ]
213
+ self.compare_all(formatter, in_out)
214
+
215
+ formatter = EngFormatter(accuracy=0, use_eng_prefix=True)
216
+ in_out = [
217
+ (5.55555, " 6"),
218
+ (55.5555, " 56"),
219
+ (555.555, " 556"),
220
+ (5555.55, " 6k"),
221
+ (55555.5, " 56k"),
222
+ (555555, " 556k"),
223
+ ]
224
+ self.compare_all(formatter, in_out)
225
+
226
+ formatter = EngFormatter(accuracy=3, use_eng_prefix=True)
227
+ result = formatter(0)
228
+ assert result == " 0.000"
229
+
230
+ def test_nan(self):
231
+ # Issue #11981
232
+
233
+ formatter = EngFormatter(accuracy=1, use_eng_prefix=True)
234
+ result = formatter(np.nan)
235
+ assert result == "NaN"
236
+
237
+ df = DataFrame(
238
+ {
239
+ "a": [1.5, 10.3, 20.5],
240
+ "b": [50.3, 60.67, 70.12],
241
+ "c": [100.2, 101.33, 120.33],
242
+ }
243
+ )
244
+ pt = df.pivot_table(values="a", index="b", columns="c")
245
+ set_eng_float_format(accuracy=1)
246
+ result = pt.to_string()
247
+ assert "NaN" in result
248
+
249
+ def test_inf(self):
250
+ # Issue #11981
251
+
252
+ formatter = EngFormatter(accuracy=1, use_eng_prefix=True)
253
+ result = formatter(np.inf)
254
+ assert result == "inf"
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/test_format.py ADDED
@@ -0,0 +1,2293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tests for the file pandas.io.formats.format, *not* tests for general formatting
3
+ of pandas objects.
4
+ """
5
+ from datetime import datetime
6
+ from io import StringIO
7
+ from pathlib import Path
8
+ import re
9
+ from shutil import get_terminal_size
10
+
11
+ import numpy as np
12
+ import pytest
13
+
14
+ from pandas._config import using_pyarrow_string_dtype
15
+
16
+ import pandas as pd
17
+ from pandas import (
18
+ DataFrame,
19
+ Index,
20
+ MultiIndex,
21
+ NaT,
22
+ Series,
23
+ Timestamp,
24
+ date_range,
25
+ get_option,
26
+ option_context,
27
+ read_csv,
28
+ reset_option,
29
+ )
30
+
31
+ from pandas.io.formats import printing
32
+ import pandas.io.formats.format as fmt
33
+
34
+
35
+ @pytest.fixture(params=["string", "pathlike", "buffer"])
36
+ def filepath_or_buffer_id(request):
37
+ """
38
+ A fixture yielding test ids for filepath_or_buffer testing.
39
+ """
40
+ return request.param
41
+
42
+
43
+ @pytest.fixture
44
+ def filepath_or_buffer(filepath_or_buffer_id, tmp_path):
45
+ """
46
+ A fixture yielding a string representing a filepath, a path-like object
47
+ and a StringIO buffer. Also checks that buffer is not closed.
48
+ """
49
+ if filepath_or_buffer_id == "buffer":
50
+ buf = StringIO()
51
+ yield buf
52
+ assert not buf.closed
53
+ else:
54
+ assert isinstance(tmp_path, Path)
55
+ if filepath_or_buffer_id == "pathlike":
56
+ yield tmp_path / "foo"
57
+ else:
58
+ yield str(tmp_path / "foo")
59
+
60
+
61
+ @pytest.fixture
62
+ def assert_filepath_or_buffer_equals(
63
+ filepath_or_buffer, filepath_or_buffer_id, encoding
64
+ ):
65
+ """
66
+ Assertion helper for checking filepath_or_buffer.
67
+ """
68
+ if encoding is None:
69
+ encoding = "utf-8"
70
+
71
+ def _assert_filepath_or_buffer_equals(expected):
72
+ if filepath_or_buffer_id == "string":
73
+ with open(filepath_or_buffer, encoding=encoding) as f:
74
+ result = f.read()
75
+ elif filepath_or_buffer_id == "pathlike":
76
+ result = filepath_or_buffer.read_text(encoding=encoding)
77
+ elif filepath_or_buffer_id == "buffer":
78
+ result = filepath_or_buffer.getvalue()
79
+ assert result == expected
80
+
81
+ return _assert_filepath_or_buffer_equals
82
+
83
+
84
+ def has_info_repr(df):
85
+ r = repr(df)
86
+ c1 = r.split("\n")[0].startswith("<class")
87
+ c2 = r.split("\n")[0].startswith(r"&lt;class") # _repr_html_
88
+ return c1 or c2
89
+
90
+
91
+ def has_non_verbose_info_repr(df):
92
+ has_info = has_info_repr(df)
93
+ r = repr(df)
94
+
95
+ # 1. <class>
96
+ # 2. Index
97
+ # 3. Columns
98
+ # 4. dtype
99
+ # 5. memory usage
100
+ # 6. trailing newline
101
+ nv = len(r.split("\n")) == 6
102
+ return has_info and nv
103
+
104
+
105
+ def has_horizontally_truncated_repr(df):
106
+ try: # Check header row
107
+ fst_line = np.array(repr(df).splitlines()[0].split())
108
+ cand_col = np.where(fst_line == "...")[0][0]
109
+ except IndexError:
110
+ return False
111
+ # Make sure each row has this ... in the same place
112
+ r = repr(df)
113
+ for ix, _ in enumerate(r.splitlines()):
114
+ if not r.split()[cand_col] == "...":
115
+ return False
116
+ return True
117
+
118
+
119
+ def has_vertically_truncated_repr(df):
120
+ r = repr(df)
121
+ only_dot_row = False
122
+ for row in r.splitlines():
123
+ if re.match(r"^[\.\ ]+$", row):
124
+ only_dot_row = True
125
+ return only_dot_row
126
+
127
+
128
+ def has_truncated_repr(df):
129
+ return has_horizontally_truncated_repr(df) or has_vertically_truncated_repr(df)
130
+
131
+
132
+ def has_doubly_truncated_repr(df):
133
+ return has_horizontally_truncated_repr(df) and has_vertically_truncated_repr(df)
134
+
135
+
136
+ def has_expanded_repr(df):
137
+ r = repr(df)
138
+ for line in r.split("\n"):
139
+ if line.endswith("\\"):
140
+ return True
141
+ return False
142
+
143
+
144
+ class TestDataFrameFormatting:
145
+ def test_repr_truncation(self):
146
+ max_len = 20
147
+ with option_context("display.max_colwidth", max_len):
148
+ df = DataFrame(
149
+ {
150
+ "A": np.random.default_rng(2).standard_normal(10),
151
+ "B": [
152
+ "a"
153
+ * np.random.default_rng(2).integers(max_len - 1, max_len + 1)
154
+ for _ in range(10)
155
+ ],
156
+ }
157
+ )
158
+ r = repr(df)
159
+ r = r[r.find("\n") + 1 :]
160
+
161
+ adj = printing.get_adjustment()
162
+
163
+ for line, value in zip(r.split("\n"), df["B"]):
164
+ if adj.len(value) + 1 > max_len:
165
+ assert "..." in line
166
+ else:
167
+ assert "..." not in line
168
+
169
+ with option_context("display.max_colwidth", 999999):
170
+ assert "..." not in repr(df)
171
+
172
+ with option_context("display.max_colwidth", max_len + 2):
173
+ assert "..." not in repr(df)
174
+
175
+ def test_repr_truncation_preserves_na(self):
176
+ # https://github.com/pandas-dev/pandas/issues/55630
177
+ df = DataFrame({"a": [pd.NA for _ in range(10)]})
178
+ with option_context("display.max_rows", 2, "display.show_dimensions", False):
179
+ assert repr(df) == " a\n0 <NA>\n.. ...\n9 <NA>"
180
+
181
+ def test_max_colwidth_negative_int_raises(self):
182
+ # Deprecation enforced from:
183
+ # https://github.com/pandas-dev/pandas/issues/31532
184
+ with pytest.raises(
185
+ ValueError, match="Value must be a nonnegative integer or None"
186
+ ):
187
+ with option_context("display.max_colwidth", -1):
188
+ pass
189
+
190
+ def test_repr_chop_threshold(self):
191
+ df = DataFrame([[0.1, 0.5], [0.5, -0.1]])
192
+ reset_option("display.chop_threshold") # default None
193
+ assert repr(df) == " 0 1\n0 0.1 0.5\n1 0.5 -0.1"
194
+
195
+ with option_context("display.chop_threshold", 0.2):
196
+ assert repr(df) == " 0 1\n0 0.0 0.5\n1 0.5 0.0"
197
+
198
+ with option_context("display.chop_threshold", 0.6):
199
+ assert repr(df) == " 0 1\n0 0.0 0.0\n1 0.0 0.0"
200
+
201
+ with option_context("display.chop_threshold", None):
202
+ assert repr(df) == " 0 1\n0 0.1 0.5\n1 0.5 -0.1"
203
+
204
+ def test_repr_chop_threshold_column_below(self):
205
+ # GH 6839: validation case
206
+
207
+ df = DataFrame([[10, 20, 30, 40], [8e-10, -1e-11, 2e-9, -2e-11]]).T
208
+
209
+ with option_context("display.chop_threshold", 0):
210
+ assert repr(df) == (
211
+ " 0 1\n"
212
+ "0 10.0 8.000000e-10\n"
213
+ "1 20.0 -1.000000e-11\n"
214
+ "2 30.0 2.000000e-09\n"
215
+ "3 40.0 -2.000000e-11"
216
+ )
217
+
218
+ with option_context("display.chop_threshold", 1e-8):
219
+ assert repr(df) == (
220
+ " 0 1\n"
221
+ "0 10.0 0.000000e+00\n"
222
+ "1 20.0 0.000000e+00\n"
223
+ "2 30.0 0.000000e+00\n"
224
+ "3 40.0 0.000000e+00"
225
+ )
226
+
227
+ with option_context("display.chop_threshold", 5e-11):
228
+ assert repr(df) == (
229
+ " 0 1\n"
230
+ "0 10.0 8.000000e-10\n"
231
+ "1 20.0 0.000000e+00\n"
232
+ "2 30.0 2.000000e-09\n"
233
+ "3 40.0 0.000000e+00"
234
+ )
235
+
236
+ def test_repr_no_backslash(self):
237
+ with option_context("mode.sim_interactive", True):
238
+ df = DataFrame(np.random.default_rng(2).standard_normal((10, 4)))
239
+ assert "\\" not in repr(df)
240
+
241
+ def test_expand_frame_repr(self):
242
+ df_small = DataFrame("hello", index=[0], columns=[0])
243
+ df_wide = DataFrame("hello", index=[0], columns=range(10))
244
+ df_tall = DataFrame("hello", index=range(30), columns=range(5))
245
+
246
+ with option_context("mode.sim_interactive", True):
247
+ with option_context(
248
+ "display.max_columns",
249
+ 10,
250
+ "display.width",
251
+ 20,
252
+ "display.max_rows",
253
+ 20,
254
+ "display.show_dimensions",
255
+ True,
256
+ ):
257
+ with option_context("display.expand_frame_repr", True):
258
+ assert not has_truncated_repr(df_small)
259
+ assert not has_expanded_repr(df_small)
260
+ assert not has_truncated_repr(df_wide)
261
+ assert has_expanded_repr(df_wide)
262
+ assert has_vertically_truncated_repr(df_tall)
263
+ assert has_expanded_repr(df_tall)
264
+
265
+ with option_context("display.expand_frame_repr", False):
266
+ assert not has_truncated_repr(df_small)
267
+ assert not has_expanded_repr(df_small)
268
+ assert not has_horizontally_truncated_repr(df_wide)
269
+ assert not has_expanded_repr(df_wide)
270
+ assert has_vertically_truncated_repr(df_tall)
271
+ assert not has_expanded_repr(df_tall)
272
+
273
+ def test_repr_non_interactive(self):
274
+ # in non interactive mode, there can be no dependency on the
275
+ # result of terminal auto size detection
276
+ df = DataFrame("hello", index=range(1000), columns=range(5))
277
+
278
+ with option_context(
279
+ "mode.sim_interactive", False, "display.width", 0, "display.max_rows", 5000
280
+ ):
281
+ assert not has_truncated_repr(df)
282
+ assert not has_expanded_repr(df)
283
+
284
+ def test_repr_truncates_terminal_size(self, monkeypatch):
285
+ # see gh-21180
286
+
287
+ terminal_size = (118, 96)
288
+ monkeypatch.setattr(
289
+ "pandas.io.formats.format.get_terminal_size", lambda: terminal_size
290
+ )
291
+
292
+ index = range(5)
293
+ columns = MultiIndex.from_tuples(
294
+ [
295
+ ("This is a long title with > 37 chars.", "cat"),
296
+ ("This is a loooooonger title with > 43 chars.", "dog"),
297
+ ]
298
+ )
299
+ df = DataFrame(1, index=index, columns=columns)
300
+
301
+ result = repr(df)
302
+
303
+ h1, h2 = result.split("\n")[:2]
304
+ assert "long" in h1
305
+ assert "loooooonger" in h1
306
+ assert "cat" in h2
307
+ assert "dog" in h2
308
+
309
+ # regular columns
310
+ df2 = DataFrame({"A" * 41: [1, 2], "B" * 41: [1, 2]})
311
+ result = repr(df2)
312
+
313
+ assert df2.columns[0] in result.split("\n")[0]
314
+
315
+ def test_repr_truncates_terminal_size_full(self, monkeypatch):
316
+ # GH 22984 ensure entire window is filled
317
+ terminal_size = (80, 24)
318
+ df = DataFrame(np.random.default_rng(2).random((1, 7)))
319
+
320
+ monkeypatch.setattr(
321
+ "pandas.io.formats.format.get_terminal_size", lambda: terminal_size
322
+ )
323
+ assert "..." not in str(df)
324
+
325
+ def test_repr_truncation_column_size(self):
326
+ # dataframe with last column very wide -> check it is not used to
327
+ # determine size of truncation (...) column
328
+ df = DataFrame(
329
+ {
330
+ "a": [108480, 30830],
331
+ "b": [12345, 12345],
332
+ "c": [12345, 12345],
333
+ "d": [12345, 12345],
334
+ "e": ["a" * 50] * 2,
335
+ }
336
+ )
337
+ assert "..." in str(df)
338
+ assert " ... " not in str(df)
339
+
340
+ def test_repr_max_columns_max_rows(self):
341
+ term_width, term_height = get_terminal_size()
342
+ if term_width < 10 or term_height < 10:
343
+ pytest.skip(f"terminal size too small, {term_width} x {term_height}")
344
+
345
+ def mkframe(n):
346
+ index = [f"{i:05d}" for i in range(n)]
347
+ return DataFrame(0, index, index)
348
+
349
+ df6 = mkframe(6)
350
+ df10 = mkframe(10)
351
+ with option_context("mode.sim_interactive", True):
352
+ with option_context("display.width", term_width * 2):
353
+ with option_context("display.max_rows", 5, "display.max_columns", 5):
354
+ assert not has_expanded_repr(mkframe(4))
355
+ assert not has_expanded_repr(mkframe(5))
356
+ assert not has_expanded_repr(df6)
357
+ assert has_doubly_truncated_repr(df6)
358
+
359
+ with option_context("display.max_rows", 20, "display.max_columns", 10):
360
+ # Out off max_columns boundary, but no extending
361
+ # since not exceeding width
362
+ assert not has_expanded_repr(df6)
363
+ assert not has_truncated_repr(df6)
364
+
365
+ with option_context("display.max_rows", 9, "display.max_columns", 10):
366
+ # out vertical bounds can not result in expanded repr
367
+ assert not has_expanded_repr(df10)
368
+ assert has_vertically_truncated_repr(df10)
369
+
370
+ # width=None in terminal, auto detection
371
+ with option_context(
372
+ "display.max_columns",
373
+ 100,
374
+ "display.max_rows",
375
+ term_width * 20,
376
+ "display.width",
377
+ None,
378
+ ):
379
+ df = mkframe((term_width // 7) - 2)
380
+ assert not has_expanded_repr(df)
381
+ df = mkframe((term_width // 7) + 2)
382
+ printing.pprint_thing(df._repr_fits_horizontal_())
383
+ assert has_expanded_repr(df)
384
+
385
+ def test_repr_min_rows(self):
386
+ df = DataFrame({"a": range(20)})
387
+
388
+ # default setting no truncation even if above min_rows
389
+ assert ".." not in repr(df)
390
+ assert ".." not in df._repr_html_()
391
+
392
+ df = DataFrame({"a": range(61)})
393
+
394
+ # default of max_rows 60 triggers truncation if above
395
+ assert ".." in repr(df)
396
+ assert ".." in df._repr_html_()
397
+
398
+ with option_context("display.max_rows", 10, "display.min_rows", 4):
399
+ # truncated after first two rows
400
+ assert ".." in repr(df)
401
+ assert "2 " not in repr(df)
402
+ assert "..." in df._repr_html_()
403
+ assert "<td>2</td>" not in df._repr_html_()
404
+
405
+ with option_context("display.max_rows", 12, "display.min_rows", None):
406
+ # when set to None, follow value of max_rows
407
+ assert "5 5" in repr(df)
408
+ assert "<td>5</td>" in df._repr_html_()
409
+
410
+ with option_context("display.max_rows", 10, "display.min_rows", 12):
411
+ # when set value higher as max_rows, use the minimum
412
+ assert "5 5" not in repr(df)
413
+ assert "<td>5</td>" not in df._repr_html_()
414
+
415
+ with option_context("display.max_rows", None, "display.min_rows", 12):
416
+ # max_rows of None -> never truncate
417
+ assert ".." not in repr(df)
418
+ assert ".." not in df._repr_html_()
419
+
420
+ def test_str_max_colwidth(self):
421
+ # GH 7856
422
+ df = DataFrame(
423
+ [
424
+ {
425
+ "a": "foo",
426
+ "b": "bar",
427
+ "c": "uncomfortably long line with lots of stuff",
428
+ "d": 1,
429
+ },
430
+ {"a": "foo", "b": "bar", "c": "stuff", "d": 1},
431
+ ]
432
+ )
433
+ df.set_index(["a", "b", "c"])
434
+ assert str(df) == (
435
+ " a b c d\n"
436
+ "0 foo bar uncomfortably long line with lots of stuff 1\n"
437
+ "1 foo bar stuff 1"
438
+ )
439
+ with option_context("max_colwidth", 20):
440
+ assert str(df) == (
441
+ " a b c d\n"
442
+ "0 foo bar uncomfortably lo... 1\n"
443
+ "1 foo bar stuff 1"
444
+ )
445
+
446
+ def test_auto_detect(self):
447
+ term_width, term_height = get_terminal_size()
448
+ fac = 1.05 # Arbitrary large factor to exceed term width
449
+ cols = range(int(term_width * fac))
450
+ index = range(10)
451
+ df = DataFrame(index=index, columns=cols)
452
+ with option_context("mode.sim_interactive", True):
453
+ with option_context("display.max_rows", None):
454
+ with option_context("display.max_columns", None):
455
+ # Wrap around with None
456
+ assert has_expanded_repr(df)
457
+ with option_context("display.max_rows", 0):
458
+ with option_context("display.max_columns", 0):
459
+ # Truncate with auto detection.
460
+ assert has_horizontally_truncated_repr(df)
461
+
462
+ index = range(int(term_height * fac))
463
+ df = DataFrame(index=index, columns=cols)
464
+ with option_context("display.max_rows", 0):
465
+ with option_context("display.max_columns", None):
466
+ # Wrap around with None
467
+ assert has_expanded_repr(df)
468
+ # Truncate vertically
469
+ assert has_vertically_truncated_repr(df)
470
+
471
+ with option_context("display.max_rows", None):
472
+ with option_context("display.max_columns", 0):
473
+ assert has_horizontally_truncated_repr(df)
474
+
475
+ def test_to_string_repr_unicode2(self):
476
+ idx = Index(["abc", "\u03c3a", "aegdvg"])
477
+ ser = Series(np.random.default_rng(2).standard_normal(len(idx)), idx)
478
+ rs = repr(ser).split("\n")
479
+ line_len = len(rs[0])
480
+ for line in rs[1:]:
481
+ try:
482
+ line = line.decode(get_option("display.encoding"))
483
+ except AttributeError:
484
+ pass
485
+ if not line.startswith("dtype:"):
486
+ assert len(line) == line_len
487
+
488
+ def test_east_asian_unicode_false(self):
489
+ # not aligned properly because of east asian width
490
+
491
+ # mid col
492
+ df = DataFrame(
493
+ {"a": ["あ", "いいい", "う", "ええええええ"], "b": [1, 222, 33333, 4]},
494
+ index=["a", "bb", "c", "ddd"],
495
+ )
496
+ expected = (
497
+ " a b\na あ 1\n"
498
+ "bb いいい 222\nc う 33333\n"
499
+ "ddd ええええええ 4"
500
+ )
501
+ assert repr(df) == expected
502
+
503
+ # last col
504
+ df = DataFrame(
505
+ {"a": [1, 222, 33333, 4], "b": ["あ", "いいい", "う", "ええええええ"]},
506
+ index=["a", "bb", "c", "ddd"],
507
+ )
508
+ expected = (
509
+ " a b\na 1 あ\n"
510
+ "bb 222 いいい\nc 33333 う\n"
511
+ "ddd 4 ええええええ"
512
+ )
513
+ assert repr(df) == expected
514
+
515
+ # all col
516
+ df = DataFrame(
517
+ {
518
+ "a": ["あああああ", "い", "う", "えええ"],
519
+ "b": ["あ", "いいい", "う", "ええええええ"],
520
+ },
521
+ index=["a", "bb", "c", "ddd"],
522
+ )
523
+ expected = (
524
+ " a b\na あああああ あ\n"
525
+ "bb い いいい\nc う う\n"
526
+ "ddd えええ ええええええ"
527
+ )
528
+ assert repr(df) == expected
529
+
530
+ # column name
531
+ df = DataFrame(
532
+ {
533
+ "b": ["あ", "いいい", "う", "ええええええ"],
534
+ "あああああ": [1, 222, 33333, 4],
535
+ },
536
+ index=["a", "bb", "c", "ddd"],
537
+ )
538
+ expected = (
539
+ " b あああああ\na あ 1\n"
540
+ "bb いいい 222\nc う 33333\n"
541
+ "ddd ええええええ 4"
542
+ )
543
+ assert repr(df) == expected
544
+
545
+ # index
546
+ df = DataFrame(
547
+ {
548
+ "a": ["あああああ", "い", "う", "えええ"],
549
+ "b": ["あ", "いいい", "う", "ええええええ"],
550
+ },
551
+ index=["あああ", "いいいいいい", "うう", "え"],
552
+ )
553
+ expected = (
554
+ " a b\nあああ あああああ あ\n"
555
+ "いいいいいい い いいい\nうう う う\n"
556
+ "え えええ ええええええ"
557
+ )
558
+ assert repr(df) == expected
559
+
560
+ # index name
561
+ df = DataFrame(
562
+ {
563
+ "a": ["あああああ", "い", "う", "えええ"],
564
+ "b": ["あ", "いいい", "う", "ええええええ"],
565
+ },
566
+ index=Index(["あ", "い", "うう", "え"], name="おおおお"),
567
+ )
568
+ expected = (
569
+ " a b\n"
570
+ "おおおお \n"
571
+ "あ あああああ あ\n"
572
+ "い い いいい\n"
573
+ "うう う う\n"
574
+ "え えええ ええええええ"
575
+ )
576
+ assert repr(df) == expected
577
+
578
+ # all
579
+ df = DataFrame(
580
+ {
581
+ "あああ": ["あああ", "い", "う", "えええええ"],
582
+ "いいいいい": ["あ", "いいい", "う", "ええ"],
583
+ },
584
+ index=Index(["あ", "いいい", "うう", "え"], name="お"),
585
+ )
586
+ expected = (
587
+ " あああ いいいいい\n"
588
+ "お \n"
589
+ "あ あああ あ\n"
590
+ "いいい い いいい\n"
591
+ "うう う う\n"
592
+ "え えええええ ええ"
593
+ )
594
+ assert repr(df) == expected
595
+
596
+ # MultiIndex
597
+ idx = MultiIndex.from_tuples(
598
+ [("あ", "いい"), ("う", "え"), ("おおお", "かかかか"), ("き", "くく")]
599
+ )
600
+ df = DataFrame(
601
+ {
602
+ "a": ["あああああ", "い", "う", "えええ"],
603
+ "b": ["あ", "いいい", "う", "ええええええ"],
604
+ },
605
+ index=idx,
606
+ )
607
+ expected = (
608
+ " a b\n"
609
+ "あ いい あああああ あ\n"
610
+ "う え い いいい\n"
611
+ "おおお かかかか う う\n"
612
+ "き くく えええ ええええええ"
613
+ )
614
+ assert repr(df) == expected
615
+
616
+ # truncate
617
+ with option_context("display.max_rows", 3, "display.max_columns", 3):
618
+ df = DataFrame(
619
+ {
620
+ "a": ["あああああ", "い", "う", "えええ"],
621
+ "b": ["あ", "いいい", "う", "ええええええ"],
622
+ "c": ["お", "か", "ききき", "くくくくくく"],
623
+ "ああああ": ["さ", "し", "す", "せ"],
624
+ },
625
+ columns=["a", "b", "c", "ああああ"],
626
+ )
627
+
628
+ expected = (
629
+ " a ... ああああ\n0 あああああ ... さ\n"
630
+ ".. ... ... ...\n3 えええ ... せ\n"
631
+ "\n[4 rows x 4 columns]"
632
+ )
633
+ assert repr(df) == expected
634
+
635
+ df.index = ["あああ", "いいいい", "う", "aaa"]
636
+ expected = (
637
+ " a ... ああああ\nあああ あああああ ... さ\n"
638
+ ".. ... ... ...\naaa えええ ... せ\n"
639
+ "\n[4 rows x 4 columns]"
640
+ )
641
+ assert repr(df) == expected
642
+
643
+ def test_east_asian_unicode_true(self):
644
+ # Enable Unicode option -----------------------------------------
645
+ with option_context("display.unicode.east_asian_width", True):
646
+ # mid col
647
+ df = DataFrame(
648
+ {"a": ["あ", "いいい", "う", "ええええええ"], "b": [1, 222, 33333, 4]},
649
+ index=["a", "bb", "c", "ddd"],
650
+ )
651
+ expected = (
652
+ " a b\na あ 1\n"
653
+ "bb いいい 222\nc う 33333\n"
654
+ "ddd ええええええ 4"
655
+ )
656
+ assert repr(df) == expected
657
+
658
+ # last col
659
+ df = DataFrame(
660
+ {"a": [1, 222, 33333, 4], "b": ["あ", "いいい", "う", "ええええええ"]},
661
+ index=["a", "bb", "c", "ddd"],
662
+ )
663
+ expected = (
664
+ " a b\na 1 あ\n"
665
+ "bb 222 いいい\nc 33333 う\n"
666
+ "ddd 4 ええええええ"
667
+ )
668
+ assert repr(df) == expected
669
+
670
+ # all col
671
+ df = DataFrame(
672
+ {
673
+ "a": ["あああああ", "い", "う", "えええ"],
674
+ "b": ["あ", "いいい", "う", "ええええええ"],
675
+ },
676
+ index=["a", "bb", "c", "ddd"],
677
+ )
678
+ expected = (
679
+ " a b\n"
680
+ "a あああああ あ\n"
681
+ "bb い いいい\n"
682
+ "c う う\n"
683
+ "ddd えええ ええええええ"
684
+ )
685
+ assert repr(df) == expected
686
+
687
+ # column name
688
+ df = DataFrame(
689
+ {
690
+ "b": ["あ", "いいい", "う", "ええええええ"],
691
+ "あああああ": [1, 222, 33333, 4],
692
+ },
693
+ index=["a", "bb", "c", "ddd"],
694
+ )
695
+ expected = (
696
+ " b あああああ\n"
697
+ "a あ 1\n"
698
+ "bb いいい 222\n"
699
+ "c う 33333\n"
700
+ "ddd ええええええ 4"
701
+ )
702
+ assert repr(df) == expected
703
+
704
+ # index
705
+ df = DataFrame(
706
+ {
707
+ "a": ["あああああ", "い", "う", "えええ"],
708
+ "b": ["あ", "いいい", "う", "ええええええ"],
709
+ },
710
+ index=["あああ", "いいいいいい", "うう", "え"],
711
+ )
712
+ expected = (
713
+ " a b\n"
714
+ "あああ あああああ あ\n"
715
+ "いいいいいい い いいい\n"
716
+ "うう う う\n"
717
+ "え えええ ええええええ"
718
+ )
719
+ assert repr(df) == expected
720
+
721
+ # index name
722
+ df = DataFrame(
723
+ {
724
+ "a": ["あああああ", "い", "う", "えええ"],
725
+ "b": ["あ", "いいい", "う", "ええええええ"],
726
+ },
727
+ index=Index(["あ", "い", "うう", "え"], name="おおおお"),
728
+ )
729
+ expected = (
730
+ " a b\n"
731
+ "おおおお \n"
732
+ "あ あああああ あ\n"
733
+ "い い いいい\n"
734
+ "うう う う\n"
735
+ "え えええ ええええええ"
736
+ )
737
+ assert repr(df) == expected
738
+
739
+ # all
740
+ df = DataFrame(
741
+ {
742
+ "あああ": ["あああ", "い", "う", "えええええ"],
743
+ "いいいいい": ["あ", "いいい", "う", "ええ"],
744
+ },
745
+ index=Index(["あ", "いいい", "うう", "え"], name="お"),
746
+ )
747
+ expected = (
748
+ " あああ いいいいい\n"
749
+ "お \n"
750
+ "あ あああ あ\n"
751
+ "いいい い いいい\n"
752
+ "うう う う\n"
753
+ "え えええええ ええ"
754
+ )
755
+ assert repr(df) == expected
756
+
757
+ # MultiIndex
758
+ idx = MultiIndex.from_tuples(
759
+ [("あ", "いい"), ("う", "え"), ("おおお", "かかかか"), ("き", "くく")]
760
+ )
761
+ df = DataFrame(
762
+ {
763
+ "a": ["あああああ", "い", "う", "えええ"],
764
+ "b": ["あ", "いいい", "う", "ええええええ"],
765
+ },
766
+ index=idx,
767
+ )
768
+ expected = (
769
+ " a b\n"
770
+ "あ いい あああああ あ\n"
771
+ "う え い いいい\n"
772
+ "おおお かかかか う う\n"
773
+ "き くく えええ ええええええ"
774
+ )
775
+ assert repr(df) == expected
776
+
777
+ # truncate
778
+ with option_context("display.max_rows", 3, "display.max_columns", 3):
779
+ df = DataFrame(
780
+ {
781
+ "a": ["あああああ", "い", "う", "えええ"],
782
+ "b": ["あ", "いいい", "う", "ええええええ"],
783
+ "c": ["お", "か", "ききき", "くくくくくく"],
784
+ "ああああ": ["さ", "し", "す", "せ"],
785
+ },
786
+ columns=["a", "b", "c", "ああああ"],
787
+ )
788
+
789
+ expected = (
790
+ " a ... ああああ\n"
791
+ "0 あああああ ... さ\n"
792
+ ".. ... ... ...\n"
793
+ "3 えええ ... せ\n"
794
+ "\n[4 rows x 4 columns]"
795
+ )
796
+ assert repr(df) == expected
797
+
798
+ df.index = ["あああ", "いいいい", "う", "aaa"]
799
+ expected = (
800
+ " a ... ああああ\n"
801
+ "あああ あああああ ... さ\n"
802
+ "... ... ... ...\n"
803
+ "aaa えええ ... せ\n"
804
+ "\n[4 rows x 4 columns]"
805
+ )
806
+ assert repr(df) == expected
807
+
808
+ # ambiguous unicode
809
+ df = DataFrame(
810
+ {
811
+ "b": ["あ", "いいい", "‘‘", "ええええ��え"],
812
+ "あああああ": [1, 222, 33333, 4],
813
+ },
814
+ index=["a", "bb", "c", "‘‘‘"],
815
+ )
816
+ expected = (
817
+ " b あああああ\n"
818
+ "a あ 1\n"
819
+ "bb いいい 222\n"
820
+ "c ‘‘ 33333\n"
821
+ "‘‘‘ ええええええ 4"
822
+ )
823
+ assert repr(df) == expected
824
+
825
+ def test_to_string_buffer_all_unicode(self):
826
+ buf = StringIO()
827
+
828
+ empty = DataFrame({"c/\u03c3": Series(dtype=object)})
829
+ nonempty = DataFrame({"c/\u03c3": Series([1, 2, 3])})
830
+
831
+ print(empty, file=buf)
832
+ print(nonempty, file=buf)
833
+
834
+ # this should work
835
+ buf.getvalue()
836
+
837
+ @pytest.mark.parametrize(
838
+ "index_scalar",
839
+ [
840
+ "a" * 10,
841
+ 1,
842
+ Timestamp(2020, 1, 1),
843
+ pd.Period("2020-01-01"),
844
+ ],
845
+ )
846
+ @pytest.mark.parametrize("h", [10, 20])
847
+ @pytest.mark.parametrize("w", [10, 20])
848
+ def test_to_string_truncate_indices(self, index_scalar, h, w):
849
+ with option_context("display.expand_frame_repr", False):
850
+ df = DataFrame(
851
+ index=[index_scalar] * h, columns=[str(i) * 10 for i in range(w)]
852
+ )
853
+ with option_context("display.max_rows", 15):
854
+ if h == 20:
855
+ assert has_vertically_truncated_repr(df)
856
+ else:
857
+ assert not has_vertically_truncated_repr(df)
858
+ with option_context("display.max_columns", 15):
859
+ if w == 20:
860
+ assert has_horizontally_truncated_repr(df)
861
+ else:
862
+ assert not has_horizontally_truncated_repr(df)
863
+ with option_context("display.max_rows", 15, "display.max_columns", 15):
864
+ if h == 20 and w == 20:
865
+ assert has_doubly_truncated_repr(df)
866
+ else:
867
+ assert not has_doubly_truncated_repr(df)
868
+
869
+ def test_to_string_truncate_multilevel(self):
870
+ arrays = [
871
+ ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
872
+ ["one", "two", "one", "two", "one", "two", "one", "two"],
873
+ ]
874
+ df = DataFrame(index=arrays, columns=arrays)
875
+ with option_context("display.max_rows", 7, "display.max_columns", 7):
876
+ assert has_doubly_truncated_repr(df)
877
+
878
+ @pytest.mark.parametrize("dtype", ["object", "datetime64[us]"])
879
+ def test_truncate_with_different_dtypes(self, dtype):
880
+ # 11594, 12045
881
+ # when truncated the dtypes of the splits can differ
882
+
883
+ # 11594
884
+ ser = Series(
885
+ [datetime(2012, 1, 1)] * 10
886
+ + [datetime(1012, 1, 2)]
887
+ + [datetime(2012, 1, 3)] * 10,
888
+ dtype=dtype,
889
+ )
890
+
891
+ with option_context("display.max_rows", 8):
892
+ result = str(ser)
893
+ assert dtype in result
894
+
895
+ def test_truncate_with_different_dtypes2(self):
896
+ # 12045
897
+ df = DataFrame({"text": ["some words"] + [None] * 9}, dtype=object)
898
+
899
+ with option_context("display.max_rows", 8, "display.max_columns", 3):
900
+ result = str(df)
901
+ assert "None" in result
902
+ assert "NaN" not in result
903
+
904
+ def test_truncate_with_different_dtypes_multiindex(self):
905
+ # GH#13000
906
+ df = DataFrame({"Vals": range(100)})
907
+ frame = pd.concat([df], keys=["Sweep"], names=["Sweep", "Index"])
908
+ result = repr(frame)
909
+
910
+ result2 = repr(frame.iloc[:5])
911
+ assert result.startswith(result2)
912
+
913
+ def test_datetimelike_frame(self):
914
+ # GH 12211
915
+ df = DataFrame({"date": [Timestamp("20130101").tz_localize("UTC")] + [NaT] * 5})
916
+
917
+ with option_context("display.max_rows", 5):
918
+ result = str(df)
919
+ assert "2013-01-01 00:00:00+00:00" in result
920
+ assert "NaT" in result
921
+ assert "..." in result
922
+ assert "[6 rows x 1 columns]" in result
923
+
924
+ dts = [Timestamp("2011-01-01", tz="US/Eastern")] * 5 + [NaT] * 5
925
+ df = DataFrame({"dt": dts, "x": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]})
926
+ with option_context("display.max_rows", 5):
927
+ expected = (
928
+ " dt x\n"
929
+ "0 2011-01-01 00:00:00-05:00 1\n"
930
+ "1 2011-01-01 00:00:00-05:00 2\n"
931
+ ".. ... ..\n"
932
+ "8 NaT 9\n"
933
+ "9 NaT 10\n\n"
934
+ "[10 rows x 2 columns]"
935
+ )
936
+ assert repr(df) == expected
937
+
938
+ dts = [NaT] * 5 + [Timestamp("2011-01-01", tz="US/Eastern")] * 5
939
+ df = DataFrame({"dt": dts, "x": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]})
940
+ with option_context("display.max_rows", 5):
941
+ expected = (
942
+ " dt x\n"
943
+ "0 NaT 1\n"
944
+ "1 NaT 2\n"
945
+ ".. ... ..\n"
946
+ "8 2011-01-01 00:00:00-05:00 9\n"
947
+ "9 2011-01-01 00:00:00-05:00 10\n\n"
948
+ "[10 rows x 2 columns]"
949
+ )
950
+ assert repr(df) == expected
951
+
952
+ dts = [Timestamp("2011-01-01", tz="Asia/Tokyo")] * 5 + [
953
+ Timestamp("2011-01-01", tz="US/Eastern")
954
+ ] * 5
955
+ df = DataFrame({"dt": dts, "x": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]})
956
+ with option_context("display.max_rows", 5):
957
+ expected = (
958
+ " dt x\n"
959
+ "0 2011-01-01 00:00:00+09:00 1\n"
960
+ "1 2011-01-01 00:00:00+09:00 2\n"
961
+ ".. ... ..\n"
962
+ "8 2011-01-01 00:00:00-05:00 9\n"
963
+ "9 2011-01-01 00:00:00-05:00 10\n\n"
964
+ "[10 rows x 2 columns]"
965
+ )
966
+ assert repr(df) == expected
967
+
968
+ @pytest.mark.parametrize(
969
+ "start_date",
970
+ [
971
+ "2017-01-01 23:59:59.999999999",
972
+ "2017-01-01 23:59:59.99999999",
973
+ "2017-01-01 23:59:59.9999999",
974
+ "2017-01-01 23:59:59.999999",
975
+ "2017-01-01 23:59:59.99999",
976
+ "2017-01-01 23:59:59.9999",
977
+ ],
978
+ )
979
+ def test_datetimeindex_highprecision(self, start_date):
980
+ # GH19030
981
+ # Check that high-precision time values for the end of day are
982
+ # included in repr for DatetimeIndex
983
+ df = DataFrame({"A": date_range(start=start_date, freq="D", periods=5)})
984
+ result = str(df)
985
+ assert start_date in result
986
+
987
+ dti = date_range(start=start_date, freq="D", periods=5)
988
+ df = DataFrame({"A": range(5)}, index=dti)
989
+ result = str(df.index)
990
+ assert start_date in result
991
+
992
+ def test_string_repr_encoding(self, datapath):
993
+ filepath = datapath("io", "parser", "data", "unicode_series.csv")
994
+ df = read_csv(filepath, header=None, encoding="latin1")
995
+ repr(df)
996
+ repr(df[1])
997
+
998
+ def test_repr_corner(self):
999
+ # representing infs poses no problems
1000
+ df = DataFrame({"foo": [-np.inf, np.inf]})
1001
+ repr(df)
1002
+
1003
+ def test_frame_info_encoding(self):
1004
+ index = ["'Til There Was You (1997)", "ldum klaka (Cold Fever) (1994)"]
1005
+ with option_context("display.max_rows", 1):
1006
+ df = DataFrame(columns=["a", "b", "c"], index=index)
1007
+ repr(df)
1008
+ repr(df.T)
1009
+
1010
+ def test_wide_repr(self):
1011
+ with option_context(
1012
+ "mode.sim_interactive",
1013
+ True,
1014
+ "display.show_dimensions",
1015
+ True,
1016
+ "display.max_columns",
1017
+ 20,
1018
+ ):
1019
+ max_cols = get_option("display.max_columns")
1020
+ df = DataFrame([["a" * 25] * (max_cols - 1)] * 10)
1021
+ with option_context("display.expand_frame_repr", False):
1022
+ rep_str = repr(df)
1023
+
1024
+ assert f"10 rows x {max_cols - 1} columns" in rep_str
1025
+ with option_context("display.expand_frame_repr", True):
1026
+ wide_repr = repr(df)
1027
+ assert rep_str != wide_repr
1028
+
1029
+ with option_context("display.width", 120):
1030
+ wider_repr = repr(df)
1031
+ assert len(wider_repr) < len(wide_repr)
1032
+
1033
+ def test_wide_repr_wide_columns(self):
1034
+ with option_context("mode.sim_interactive", True, "display.max_columns", 20):
1035
+ df = DataFrame(
1036
+ np.random.default_rng(2).standard_normal((5, 3)),
1037
+ columns=["a" * 90, "b" * 90, "c" * 90],
1038
+ )
1039
+ rep_str = repr(df)
1040
+
1041
+ assert len(rep_str.splitlines()) == 20
1042
+
1043
+ def test_wide_repr_named(self):
1044
+ with option_context("mode.sim_interactive", True, "display.max_columns", 20):
1045
+ max_cols = get_option("display.max_columns")
1046
+ df = DataFrame([["a" * 25] * (max_cols - 1)] * 10)
1047
+ df.index.name = "DataFrame Index"
1048
+ with option_context("display.expand_frame_repr", False):
1049
+ rep_str = repr(df)
1050
+ with option_context("display.expand_frame_repr", True):
1051
+ wide_repr = repr(df)
1052
+ assert rep_str != wide_repr
1053
+
1054
+ with option_context("display.width", 150):
1055
+ wider_repr = repr(df)
1056
+ assert len(wider_repr) < len(wide_repr)
1057
+
1058
+ for line in wide_repr.splitlines()[1::13]:
1059
+ assert "DataFrame Index" in line
1060
+
1061
+ def test_wide_repr_multiindex(self):
1062
+ with option_context("mode.sim_interactive", True, "display.max_columns", 20):
1063
+ midx = MultiIndex.from_arrays([["a" * 5] * 10] * 2)
1064
+ max_cols = get_option("display.max_columns")
1065
+ df = DataFrame([["a" * 25] * (max_cols - 1)] * 10, index=midx)
1066
+ df.index.names = ["Level 0", "Level 1"]
1067
+ with option_context("display.expand_frame_repr", False):
1068
+ rep_str = repr(df)
1069
+ with option_context("display.expand_frame_repr", True):
1070
+ wide_repr = repr(df)
1071
+ assert rep_str != wide_repr
1072
+
1073
+ with option_context("display.width", 150):
1074
+ wider_repr = repr(df)
1075
+ assert len(wider_repr) < len(wide_repr)
1076
+
1077
+ for line in wide_repr.splitlines()[1::13]:
1078
+ assert "Level 0 Level 1" in line
1079
+
1080
+ def test_wide_repr_multiindex_cols(self):
1081
+ with option_context("mode.sim_interactive", True, "display.max_columns", 20):
1082
+ max_cols = get_option("display.max_columns")
1083
+ midx = MultiIndex.from_arrays([["a" * 5] * 10] * 2)
1084
+ mcols = MultiIndex.from_arrays([["b" * 3] * (max_cols - 1)] * 2)
1085
+ df = DataFrame(
1086
+ [["c" * 25] * (max_cols - 1)] * 10, index=midx, columns=mcols
1087
+ )
1088
+ df.index.names = ["Level 0", "Level 1"]
1089
+ with option_context("display.expand_frame_repr", False):
1090
+ rep_str = repr(df)
1091
+ with option_context("display.expand_frame_repr", True):
1092
+ wide_repr = repr(df)
1093
+ assert rep_str != wide_repr
1094
+
1095
+ with option_context("display.width", 150, "display.max_columns", 20):
1096
+ wider_repr = repr(df)
1097
+ assert len(wider_repr) < len(wide_repr)
1098
+
1099
+ def test_wide_repr_unicode(self):
1100
+ with option_context("mode.sim_interactive", True, "display.max_columns", 20):
1101
+ max_cols = 20
1102
+ df = DataFrame([["a" * 25] * 10] * (max_cols - 1))
1103
+ with option_context("display.expand_frame_repr", False):
1104
+ rep_str = repr(df)
1105
+ with option_context("display.expand_frame_repr", True):
1106
+ wide_repr = repr(df)
1107
+ assert rep_str != wide_repr
1108
+
1109
+ with option_context("display.width", 150):
1110
+ wider_repr = repr(df)
1111
+ assert len(wider_repr) < len(wide_repr)
1112
+
1113
+ def test_wide_repr_wide_long_columns(self):
1114
+ with option_context("mode.sim_interactive", True):
1115
+ df = DataFrame({"a": ["a" * 30, "b" * 30], "b": ["c" * 70, "d" * 80]})
1116
+
1117
+ result = repr(df)
1118
+ assert "ccccc" in result
1119
+ assert "ddddd" in result
1120
+
1121
+ def test_long_series(self):
1122
+ n = 1000
1123
+ s = Series(
1124
+ np.random.default_rng(2).integers(-50, 50, n),
1125
+ index=[f"s{x:04d}" for x in range(n)],
1126
+ dtype="int64",
1127
+ )
1128
+
1129
+ str_rep = str(s)
1130
+ nmatches = len(re.findall("dtype", str_rep))
1131
+ assert nmatches == 1
1132
+
1133
+ def test_to_string_ascii_error(self):
1134
+ data = [
1135
+ (
1136
+ "0 ",
1137
+ " .gitignore ",
1138
+ " 5 ",
1139
+ " \xe2\x80\xa2\xe2\x80\xa2\xe2\x80\xa2\xe2\x80\xa2\xe2\x80\xa2",
1140
+ )
1141
+ ]
1142
+ df = DataFrame(data)
1143
+
1144
+ # it works!
1145
+ repr(df)
1146
+
1147
+ def test_show_dimensions(self):
1148
+ df = DataFrame(123, index=range(10, 15), columns=range(30))
1149
+
1150
+ with option_context(
1151
+ "display.max_rows",
1152
+ 10,
1153
+ "display.max_columns",
1154
+ 40,
1155
+ "display.width",
1156
+ 500,
1157
+ "display.expand_frame_repr",
1158
+ "info",
1159
+ "display.show_dimensions",
1160
+ True,
1161
+ ):
1162
+ assert "5 rows" in str(df)
1163
+ assert "5 rows" in df._repr_html_()
1164
+ with option_context(
1165
+ "display.max_rows",
1166
+ 10,
1167
+ "display.max_columns",
1168
+ 40,
1169
+ "display.width",
1170
+ 500,
1171
+ "display.expand_frame_repr",
1172
+ "info",
1173
+ "display.show_dimensions",
1174
+ False,
1175
+ ):
1176
+ assert "5 rows" not in str(df)
1177
+ assert "5 rows" not in df._repr_html_()
1178
+ with option_context(
1179
+ "display.max_rows",
1180
+ 2,
1181
+ "display.max_columns",
1182
+ 2,
1183
+ "display.width",
1184
+ 500,
1185
+ "display.expand_frame_repr",
1186
+ "info",
1187
+ "display.show_dimensions",
1188
+ "truncate",
1189
+ ):
1190
+ assert "5 rows" in str(df)
1191
+ assert "5 rows" in df._repr_html_()
1192
+ with option_context(
1193
+ "display.max_rows",
1194
+ 10,
1195
+ "display.max_columns",
1196
+ 40,
1197
+ "display.width",
1198
+ 500,
1199
+ "display.expand_frame_repr",
1200
+ "info",
1201
+ "display.show_dimensions",
1202
+ "truncate",
1203
+ ):
1204
+ assert "5 rows" not in str(df)
1205
+ assert "5 rows" not in df._repr_html_()
1206
+
1207
+ def test_info_repr(self):
1208
+ # GH#21746 For tests inside a terminal (i.e. not CI) we need to detect
1209
+ # the terminal size to ensure that we try to print something "too big"
1210
+ term_width, term_height = get_terminal_size()
1211
+
1212
+ max_rows = 60
1213
+ max_cols = 20 + (max(term_width, 80) - 80) // 4
1214
+ # Long
1215
+ h, w = max_rows + 1, max_cols - 1
1216
+ df = DataFrame({k: np.arange(1, 1 + h) for k in np.arange(w)})
1217
+ assert has_vertically_truncated_repr(df)
1218
+ with option_context("display.large_repr", "info"):
1219
+ assert has_info_repr(df)
1220
+
1221
+ # Wide
1222
+ h, w = max_rows - 1, max_cols + 1
1223
+ df = DataFrame({k: np.arange(1, 1 + h) for k in np.arange(w)})
1224
+ assert has_horizontally_truncated_repr(df)
1225
+ with option_context(
1226
+ "display.large_repr", "info", "display.max_columns", max_cols
1227
+ ):
1228
+ assert has_info_repr(df)
1229
+
1230
+ def test_info_repr_max_cols(self):
1231
+ # GH #6939
1232
+ df = DataFrame(np.random.default_rng(2).standard_normal((10, 5)))
1233
+ with option_context(
1234
+ "display.large_repr",
1235
+ "info",
1236
+ "display.max_columns",
1237
+ 1,
1238
+ "display.max_info_columns",
1239
+ 4,
1240
+ ):
1241
+ assert has_non_verbose_info_repr(df)
1242
+
1243
+ with option_context(
1244
+ "display.large_repr",
1245
+ "info",
1246
+ "display.max_columns",
1247
+ 1,
1248
+ "display.max_info_columns",
1249
+ 5,
1250
+ ):
1251
+ assert not has_non_verbose_info_repr(df)
1252
+
1253
+ # FIXME: don't leave commented-out
1254
+ # test verbose overrides
1255
+ # set_option('display.max_info_columns', 4) # exceeded
1256
+
1257
+ def test_pprint_pathological_object(self):
1258
+ """
1259
+ If the test fails, it at least won't hang.
1260
+ """
1261
+
1262
+ class A:
1263
+ def __getitem__(self, key):
1264
+ return 3 # obviously simplified
1265
+
1266
+ df = DataFrame([A()])
1267
+ repr(df) # just don't die
1268
+
1269
+ def test_float_trim_zeros(self):
1270
+ vals = [
1271
+ 2.08430917305e10,
1272
+ 3.52205017305e10,
1273
+ 2.30674817305e10,
1274
+ 2.03954217305e10,
1275
+ 5.59897817305e10,
1276
+ ]
1277
+ skip = True
1278
+ for line in repr(DataFrame({"A": vals})).split("\n")[:-2]:
1279
+ if line.startswith("dtype:"):
1280
+ continue
1281
+ if _three_digit_exp():
1282
+ assert ("+010" in line) or skip
1283
+ else:
1284
+ assert ("+10" in line) or skip
1285
+ skip = False
1286
+
1287
+ @pytest.mark.parametrize(
1288
+ "data, expected",
1289
+ [
1290
+ (["3.50"], "0 3.50\ndtype: object"),
1291
+ ([1.20, "1.00"], "0 1.2\n1 1.00\ndtype: object"),
1292
+ ([np.nan], "0 NaN\ndtype: float64"),
1293
+ ([None], "0 None\ndtype: object"),
1294
+ (["3.50", np.nan], "0 3.50\n1 NaN\ndtype: object"),
1295
+ ([3.50, np.nan], "0 3.5\n1 NaN\ndtype: float64"),
1296
+ ([3.50, np.nan, "3.50"], "0 3.5\n1 NaN\n2 3.50\ndtype: object"),
1297
+ ([3.50, None, "3.50"], "0 3.5\n1 None\n2 3.50\ndtype: object"),
1298
+ ],
1299
+ )
1300
+ def test_repr_str_float_truncation(self, data, expected, using_infer_string):
1301
+ # GH#38708
1302
+ series = Series(data, dtype=object if "3.50" in data else None)
1303
+ result = repr(series)
1304
+ assert result == expected
1305
+
1306
+ @pytest.mark.parametrize(
1307
+ "float_format,expected",
1308
+ [
1309
+ ("{:,.0f}".format, "0 1,000\n1 test\ndtype: object"),
1310
+ ("{:.4f}".format, "0 1000.0000\n1 test\ndtype: object"),
1311
+ ],
1312
+ )
1313
+ def test_repr_float_format_in_object_col(self, float_format, expected):
1314
+ # GH#40024
1315
+ df = Series([1000.0, "test"])
1316
+ with option_context("display.float_format", float_format):
1317
+ result = repr(df)
1318
+
1319
+ assert result == expected
1320
+
1321
+ def test_period(self):
1322
+ # GH 12615
1323
+ df = DataFrame(
1324
+ {
1325
+ "A": pd.period_range("2013-01", periods=4, freq="M"),
1326
+ "B": [
1327
+ pd.Period("2011-01", freq="M"),
1328
+ pd.Period("2011-02-01", freq="D"),
1329
+ pd.Period("2011-03-01 09:00", freq="h"),
1330
+ pd.Period("2011-04", freq="M"),
1331
+ ],
1332
+ "C": list("abcd"),
1333
+ }
1334
+ )
1335
+ exp = (
1336
+ " A B C\n"
1337
+ "0 2013-01 2011-01 a\n"
1338
+ "1 2013-02 2011-02-01 b\n"
1339
+ "2 2013-03 2011-03-01 09:00 c\n"
1340
+ "3 2013-04 2011-04 d"
1341
+ )
1342
+ assert str(df) == exp
1343
+
1344
+ @pytest.mark.parametrize(
1345
+ "length, max_rows, min_rows, expected",
1346
+ [
1347
+ (10, 10, 10, 10),
1348
+ (10, 10, None, 10),
1349
+ (10, 8, None, 8),
1350
+ (20, 30, 10, 30), # max_rows > len(frame), hence max_rows
1351
+ (50, 30, 10, 10), # max_rows < len(frame), hence min_rows
1352
+ (100, 60, 10, 10), # same
1353
+ (60, 60, 10, 60), # edge case
1354
+ (61, 60, 10, 10), # edge case
1355
+ ],
1356
+ )
1357
+ def test_max_rows_fitted(self, length, min_rows, max_rows, expected):
1358
+ """Check that display logic is correct.
1359
+
1360
+ GH #37359
1361
+
1362
+ See description here:
1363
+ https://pandas.pydata.org/docs/dev/user_guide/options.html#frequently-used-options
1364
+ """
1365
+ formatter = fmt.DataFrameFormatter(
1366
+ DataFrame(np.random.default_rng(2).random((length, 3))),
1367
+ max_rows=max_rows,
1368
+ min_rows=min_rows,
1369
+ )
1370
+ result = formatter.max_rows_fitted
1371
+ assert result == expected
1372
+
1373
+
1374
+ def gen_series_formatting():
1375
+ s1 = Series(["a"] * 100)
1376
+ s2 = Series(["ab"] * 100)
1377
+ s3 = Series(["a", "ab", "abc", "abcd", "abcde", "abcdef"])
1378
+ s4 = s3[::-1]
1379
+ test_sers = {"onel": s1, "twol": s2, "asc": s3, "desc": s4}
1380
+ return test_sers
1381
+
1382
+
1383
+ class TestSeriesFormatting:
1384
+ def test_freq_name_separation(self):
1385
+ s = Series(
1386
+ np.random.default_rng(2).standard_normal(10),
1387
+ index=date_range("1/1/2000", periods=10),
1388
+ name=0,
1389
+ )
1390
+
1391
+ result = repr(s)
1392
+ assert "Freq: D, Name: 0" in result
1393
+
1394
+ def test_unicode_name_in_footer(self):
1395
+ s = Series([1, 2], name="\u05e2\u05d1\u05e8\u05d9\u05ea")
1396
+ sf = fmt.SeriesFormatter(s, name="\u05e2\u05d1\u05e8\u05d9\u05ea")
1397
+ sf._get_footer() # should not raise exception
1398
+
1399
+ @pytest.mark.xfail(
1400
+ using_pyarrow_string_dtype(), reason="Fixup when arrow is default"
1401
+ )
1402
+ def test_east_asian_unicode_series(self):
1403
+ # not aligned properly because of east asian width
1404
+
1405
+ # unicode index
1406
+ s = Series(["a", "bb", "CCC", "D"], index=["あ", "いい", "ううう", "ええええ"])
1407
+ expected = "".join(
1408
+ [
1409
+ "あ a\n",
1410
+ "いい bb\n",
1411
+ "ううう CCC\n",
1412
+ "ええええ D\ndtype: object",
1413
+ ]
1414
+ )
1415
+ assert repr(s) == expected
1416
+
1417
+ # unicode values
1418
+ s = Series(["あ", "いい", "ううう", "ええええ"], index=["a", "bb", "c", "ddd"])
1419
+ expected = "".join(
1420
+ [
1421
+ "a あ\n",
1422
+ "bb いい\n",
1423
+ "c ううう\n",
1424
+ "ddd ええええ\n",
1425
+ "dtype: object",
1426
+ ]
1427
+ )
1428
+
1429
+ assert repr(s) == expected
1430
+
1431
+ # both
1432
+ s = Series(
1433
+ ["あ", "いい", "ううう", "ええええ"],
1434
+ index=["ああ", "いいいい", "う", "えええ"],
1435
+ )
1436
+ expected = "".join(
1437
+ [
1438
+ "ああ あ\n",
1439
+ "いいいい いい\n",
1440
+ "う ううう\n",
1441
+ "えええ ええええ\n",
1442
+ "dtype: object",
1443
+ ]
1444
+ )
1445
+
1446
+ assert repr(s) == expected
1447
+
1448
+ # unicode footer
1449
+ s = Series(
1450
+ ["あ", "いい", "ううう", "ええええ"],
1451
+ index=["ああ", "いいいい", "う", "えええ"],
1452
+ name="おおおおおおお",
1453
+ )
1454
+ expected = (
1455
+ "ああ あ\nいいいい いい\nう ううう\n"
1456
+ "えええ ええええ\nName: おおおおおおお, dtype: object"
1457
+ )
1458
+ assert repr(s) == expected
1459
+
1460
+ # MultiIndex
1461
+ idx = MultiIndex.from_tuples(
1462
+ [("あ", "いい"), ("う", "え"), ("おおお", "かかかか"), ("き", "くく")]
1463
+ )
1464
+ s = Series([1, 22, 3333, 44444], index=idx)
1465
+ expected = (
1466
+ "あ いい 1\n"
1467
+ "う え 22\n"
1468
+ "おおお かかかか 3333\n"
1469
+ "き くく 44444\ndtype: int64"
1470
+ )
1471
+ assert repr(s) == expected
1472
+
1473
+ # object dtype, shorter than unicode repr
1474
+ s = Series([1, 22, 3333, 44444], index=[1, "AB", np.nan, "あああ"])
1475
+ expected = (
1476
+ "1 1\nAB 22\nNaN 3333\nあああ 44444\ndtype: int64"
1477
+ )
1478
+ assert repr(s) == expected
1479
+
1480
+ # object dtype, longer than unicode repr
1481
+ s = Series(
1482
+ [1, 22, 3333, 44444], index=[1, "AB", Timestamp("2011-01-01"), "あああ"]
1483
+ )
1484
+ expected = (
1485
+ "1 1\n"
1486
+ "AB 22\n"
1487
+ "2011-01-01 00:00:00 3333\n"
1488
+ "あああ 44444\ndtype: int64"
1489
+ )
1490
+ assert repr(s) == expected
1491
+
1492
+ # truncate
1493
+ with option_context("display.max_rows", 3):
1494
+ s = Series(["あ", "いい", "ううう", "ええええ"], name="おおおおおおお")
1495
+
1496
+ expected = (
1497
+ "0 あ\n ... \n"
1498
+ "3 ええええ\n"
1499
+ "Name: おおおおおおお, Length: 4, dtype: object"
1500
+ )
1501
+ assert repr(s) == expected
1502
+
1503
+ s.index = ["ああ", "いいいい", "う", "えええ"]
1504
+ expected = (
1505
+ "ああ あ\n ... \n"
1506
+ "えええ ええええ\n"
1507
+ "Name: おおおおおおお, Length: 4, dtype: object"
1508
+ )
1509
+ assert repr(s) == expected
1510
+
1511
+ # Enable Unicode option -----------------------------------------
1512
+ with option_context("display.unicode.east_asian_width", True):
1513
+ # unicode index
1514
+ s = Series(
1515
+ ["a", "bb", "CCC", "D"],
1516
+ index=["あ", "いい", "ううう", "ええええ"],
1517
+ )
1518
+ expected = (
1519
+ "あ a\nいい bb\nううう CCC\n"
1520
+ "ええええ D\ndtype: object"
1521
+ )
1522
+ assert repr(s) == expected
1523
+
1524
+ # unicode values
1525
+ s = Series(
1526
+ ["あ", "いい", "ううう", "ええええ"],
1527
+ index=["a", "bb", "c", "ddd"],
1528
+ )
1529
+ expected = (
1530
+ "a あ\nbb いい\nc ううう\n"
1531
+ "ddd ええええ\ndtype: object"
1532
+ )
1533
+ assert repr(s) == expected
1534
+ # both
1535
+ s = Series(
1536
+ ["あ", "いい", "ううう", "ええええ"],
1537
+ index=["ああ", "いいいい", "う", "えええ"],
1538
+ )
1539
+ expected = (
1540
+ "ああ あ\n"
1541
+ "いいいい いい\n"
1542
+ "う ううう\n"
1543
+ "えええ ええええ\ndtype: object"
1544
+ )
1545
+ assert repr(s) == expected
1546
+
1547
+ # unicode footer
1548
+ s = Series(
1549
+ ["あ", "いい", "ううう", "ええええ"],
1550
+ index=["ああ", "いいいい", "う", "えええ"],
1551
+ name="おおおおおおお",
1552
+ )
1553
+ expected = (
1554
+ "ああ あ\n"
1555
+ "いいいい いい\n"
1556
+ "う ううう\n"
1557
+ "えええ ええええ\n"
1558
+ "Name: おおおおおおお, dtype: object"
1559
+ )
1560
+ assert repr(s) == expected
1561
+
1562
+ # MultiIndex
1563
+ idx = MultiIndex.from_tuples(
1564
+ [("あ", "いい"), ("う", "え"), ("おおお", "かかかか"), ("き", "くく")]
1565
+ )
1566
+ s = Series([1, 22, 3333, 44444], index=idx)
1567
+ expected = (
1568
+ "あ いい 1\n"
1569
+ "う え 22\n"
1570
+ "おおお かかかか 3333\n"
1571
+ "き くく 44444\n"
1572
+ "dtype: int64"
1573
+ )
1574
+ assert repr(s) == expected
1575
+
1576
+ # object dtype, shorter than unicode repr
1577
+ s = Series([1, 22, 3333, 44444], index=[1, "AB", np.nan, "あああ"])
1578
+ expected = (
1579
+ "1 1\nAB 22\nNaN 3333\n"
1580
+ "あああ 44444\ndtype: int64"
1581
+ )
1582
+ assert repr(s) == expected
1583
+
1584
+ # object dtype, longer than unicode repr
1585
+ s = Series(
1586
+ [1, 22, 3333, 44444],
1587
+ index=[1, "AB", Timestamp("2011-01-01"), "あああ"],
1588
+ )
1589
+ expected = (
1590
+ "1 1\n"
1591
+ "AB 22\n"
1592
+ "2011-01-01 00:00:00 3333\n"
1593
+ "あああ 44444\ndtype: int64"
1594
+ )
1595
+ assert repr(s) == expected
1596
+
1597
+ # truncate
1598
+ with option_context("display.max_rows", 3):
1599
+ s = Series(["あ", "いい", "ううう", "ええええ"], name="おおおおおおお")
1600
+ expected = (
1601
+ "0 あ\n ... \n"
1602
+ "3 ええええ\n"
1603
+ "Name: おおおおおおお, Length: 4, dtype: object"
1604
+ )
1605
+ assert repr(s) == expected
1606
+
1607
+ s.index = ["ああ", "いいいい", "う", "えええ"]
1608
+ expected = (
1609
+ "ああ あ\n"
1610
+ " ... \n"
1611
+ "えええ ええええ\n"
1612
+ "Name: おおおおおおお, Length: 4, dtype: object"
1613
+ )
1614
+ assert repr(s) == expected
1615
+
1616
+ # ambiguous unicode
1617
+ s = Series(
1618
+ ["‘‘", "い‘‘", "ううう", "ええええ"],
1619
+ index=["ああ", "‘‘‘‘いい", "‘‘", "えええ"],
1620
+ )
1621
+ expected = (
1622
+ "ああ ‘‘\n"
1623
+ "‘‘‘‘いい い‘‘\n"
1624
+ "‘‘ ううう\n"
1625
+ "えええ ええええ\ndtype: object"
1626
+ )
1627
+ assert repr(s) == expected
1628
+
1629
+ def test_float_trim_zeros(self):
1630
+ vals = [
1631
+ 2.08430917305e10,
1632
+ 3.52205017305e10,
1633
+ 2.30674817305e10,
1634
+ 2.03954217305e10,
1635
+ 5.59897817305e10,
1636
+ ]
1637
+ for line in repr(Series(vals)).split("\n"):
1638
+ if line.startswith("dtype:"):
1639
+ continue
1640
+ if _three_digit_exp():
1641
+ assert "+010" in line
1642
+ else:
1643
+ assert "+10" in line
1644
+
1645
+ @pytest.mark.parametrize(
1646
+ "start_date",
1647
+ [
1648
+ "2017-01-01 23:59:59.999999999",
1649
+ "2017-01-01 23:59:59.99999999",
1650
+ "2017-01-01 23:59:59.9999999",
1651
+ "2017-01-01 23:59:59.999999",
1652
+ "2017-01-01 23:59:59.99999",
1653
+ "2017-01-01 23:59:59.9999",
1654
+ ],
1655
+ )
1656
+ def test_datetimeindex_highprecision(self, start_date):
1657
+ # GH19030
1658
+ # Check that high-precision time values for the end of day are
1659
+ # included in repr for DatetimeIndex
1660
+ s1 = Series(date_range(start=start_date, freq="D", periods=5))
1661
+ result = str(s1)
1662
+ assert start_date in result
1663
+
1664
+ dti = date_range(start=start_date, freq="D", periods=5)
1665
+ s2 = Series(3, index=dti)
1666
+ result = str(s2.index)
1667
+ assert start_date in result
1668
+
1669
+ def test_mixed_datetime64(self):
1670
+ df = DataFrame({"A": [1, 2], "B": ["2012-01-01", "2012-01-02"]})
1671
+ df["B"] = pd.to_datetime(df.B)
1672
+
1673
+ result = repr(df.loc[0])
1674
+ assert "2012-01-01" in result
1675
+
1676
+ def test_period(self):
1677
+ # GH 12615
1678
+ index = pd.period_range("2013-01", periods=6, freq="M")
1679
+ s = Series(np.arange(6, dtype="int64"), index=index)
1680
+ exp = (
1681
+ "2013-01 0\n"
1682
+ "2013-02 1\n"
1683
+ "2013-03 2\n"
1684
+ "2013-04 3\n"
1685
+ "2013-05 4\n"
1686
+ "2013-06 5\n"
1687
+ "Freq: M, dtype: int64"
1688
+ )
1689
+ assert str(s) == exp
1690
+
1691
+ s = Series(index)
1692
+ exp = (
1693
+ "0 2013-01\n"
1694
+ "1 2013-02\n"
1695
+ "2 2013-03\n"
1696
+ "3 2013-04\n"
1697
+ "4 2013-05\n"
1698
+ "5 2013-06\n"
1699
+ "dtype: period[M]"
1700
+ )
1701
+ assert str(s) == exp
1702
+
1703
+ # periods with mixed freq
1704
+ s = Series(
1705
+ [
1706
+ pd.Period("2011-01", freq="M"),
1707
+ pd.Period("2011-02-01", freq="D"),
1708
+ pd.Period("2011-03-01 09:00", freq="h"),
1709
+ ]
1710
+ )
1711
+ exp = (
1712
+ "0 2011-01\n1 2011-02-01\n"
1713
+ "2 2011-03-01 09:00\ndtype: object"
1714
+ )
1715
+ assert str(s) == exp
1716
+
1717
+ def test_max_multi_index_display(self):
1718
+ # GH 7101
1719
+
1720
+ # doc example (indexing.rst)
1721
+
1722
+ # multi-index
1723
+ arrays = [
1724
+ ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
1725
+ ["one", "two", "one", "two", "one", "two", "one", "two"],
1726
+ ]
1727
+ tuples = list(zip(*arrays))
1728
+ index = MultiIndex.from_tuples(tuples, names=["first", "second"])
1729
+ s = Series(np.random.default_rng(2).standard_normal(8), index=index)
1730
+
1731
+ with option_context("display.max_rows", 10):
1732
+ assert len(str(s).split("\n")) == 10
1733
+ with option_context("display.max_rows", 3):
1734
+ assert len(str(s).split("\n")) == 5
1735
+ with option_context("display.max_rows", 2):
1736
+ assert len(str(s).split("\n")) == 5
1737
+ with option_context("display.max_rows", 1):
1738
+ assert len(str(s).split("\n")) == 4
1739
+ with option_context("display.max_rows", 0):
1740
+ assert len(str(s).split("\n")) == 10
1741
+
1742
+ # index
1743
+ s = Series(np.random.default_rng(2).standard_normal(8), None)
1744
+
1745
+ with option_context("display.max_rows", 10):
1746
+ assert len(str(s).split("\n")) == 9
1747
+ with option_context("display.max_rows", 3):
1748
+ assert len(str(s).split("\n")) == 4
1749
+ with option_context("display.max_rows", 2):
1750
+ assert len(str(s).split("\n")) == 4
1751
+ with option_context("display.max_rows", 1):
1752
+ assert len(str(s).split("\n")) == 3
1753
+ with option_context("display.max_rows", 0):
1754
+ assert len(str(s).split("\n")) == 9
1755
+
1756
+ # Make sure #8532 is fixed
1757
+ def test_consistent_format(self):
1758
+ s = Series([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.9999, 1, 1] * 10)
1759
+ with option_context("display.max_rows", 10, "display.show_dimensions", False):
1760
+ res = repr(s)
1761
+ exp = (
1762
+ "0 1.0000\n1 1.0000\n2 1.0000\n3 "
1763
+ "1.0000\n4 1.0000\n ... \n125 "
1764
+ "1.0000\n126 1.0000\n127 0.9999\n128 "
1765
+ "1.0000\n129 1.0000\ndtype: float64"
1766
+ )
1767
+ assert res == exp
1768
+
1769
+ def chck_ncols(self, s):
1770
+ lines = [
1771
+ line for line in repr(s).split("\n") if not re.match(r"[^\.]*\.+", line)
1772
+ ][:-1]
1773
+ ncolsizes = len({len(line.strip()) for line in lines})
1774
+ assert ncolsizes == 1
1775
+
1776
+ @pytest.mark.xfail(
1777
+ using_pyarrow_string_dtype(), reason="change when arrow is default"
1778
+ )
1779
+ def test_format_explicit(self):
1780
+ test_sers = gen_series_formatting()
1781
+ with option_context("display.max_rows", 4, "display.show_dimensions", False):
1782
+ res = repr(test_sers["onel"])
1783
+ exp = "0 a\n1 a\n ..\n98 a\n99 a\ndtype: object"
1784
+ assert exp == res
1785
+ res = repr(test_sers["twol"])
1786
+ exp = "0 ab\n1 ab\n ..\n98 ab\n99 ab\ndtype: object"
1787
+ assert exp == res
1788
+ res = repr(test_sers["asc"])
1789
+ exp = (
1790
+ "0 a\n1 ab\n ... \n4 abcde\n5 "
1791
+ "abcdef\ndtype: object"
1792
+ )
1793
+ assert exp == res
1794
+ res = repr(test_sers["desc"])
1795
+ exp = (
1796
+ "5 abcdef\n4 abcde\n ... \n1 ab\n0 "
1797
+ "a\ndtype: object"
1798
+ )
1799
+ assert exp == res
1800
+
1801
+ def test_ncols(self):
1802
+ test_sers = gen_series_formatting()
1803
+ for s in test_sers.values():
1804
+ self.chck_ncols(s)
1805
+
1806
+ def test_max_rows_eq_one(self):
1807
+ s = Series(range(10), dtype="int64")
1808
+ with option_context("display.max_rows", 1):
1809
+ strrepr = repr(s).split("\n")
1810
+ exp1 = ["0", "0"]
1811
+ res1 = strrepr[0].split()
1812
+ assert exp1 == res1
1813
+ exp2 = [".."]
1814
+ res2 = strrepr[1].split()
1815
+ assert exp2 == res2
1816
+
1817
+ def test_truncate_ndots(self):
1818
+ def getndots(s):
1819
+ return len(re.match(r"[^\.]*(\.*)", s).groups()[0])
1820
+
1821
+ s = Series([0, 2, 3, 6])
1822
+ with option_context("display.max_rows", 2):
1823
+ strrepr = repr(s).replace("\n", "")
1824
+ assert getndots(strrepr) == 2
1825
+
1826
+ s = Series([0, 100, 200, 400])
1827
+ with option_context("display.max_rows", 2):
1828
+ strrepr = repr(s).replace("\n", "")
1829
+ assert getndots(strrepr) == 3
1830
+
1831
+ def test_show_dimensions(self):
1832
+ # gh-7117
1833
+ s = Series(range(5))
1834
+
1835
+ assert "Length" not in repr(s)
1836
+
1837
+ with option_context("display.max_rows", 4):
1838
+ assert "Length" in repr(s)
1839
+
1840
+ with option_context("display.show_dimensions", True):
1841
+ assert "Length" in repr(s)
1842
+
1843
+ with option_context("display.max_rows", 4, "display.show_dimensions", False):
1844
+ assert "Length" not in repr(s)
1845
+
1846
+ def test_repr_min_rows(self):
1847
+ s = Series(range(20))
1848
+
1849
+ # default setting no truncation even if above min_rows
1850
+ assert ".." not in repr(s)
1851
+
1852
+ s = Series(range(61))
1853
+
1854
+ # default of max_rows 60 triggers truncation if above
1855
+ assert ".." in repr(s)
1856
+
1857
+ with option_context("display.max_rows", 10, "display.min_rows", 4):
1858
+ # truncated after first two rows
1859
+ assert ".." in repr(s)
1860
+ assert "2 " not in repr(s)
1861
+
1862
+ with option_context("display.max_rows", 12, "display.min_rows", None):
1863
+ # when set to None, follow value of max_rows
1864
+ assert "5 5" in repr(s)
1865
+
1866
+ with option_context("display.max_rows", 10, "display.min_rows", 12):
1867
+ # when set value higher as max_rows, use the minimum
1868
+ assert "5 5" not in repr(s)
1869
+
1870
+ with option_context("display.max_rows", None, "display.min_rows", 12):
1871
+ # max_rows of None -> never truncate
1872
+ assert ".." not in repr(s)
1873
+
1874
+
1875
+ class TestGenericArrayFormatter:
1876
+ def test_1d_array(self):
1877
+ # _GenericArrayFormatter is used on types for which there isn't a dedicated
1878
+ # formatter. np.bool_ is one of those types.
1879
+ obj = fmt._GenericArrayFormatter(np.array([True, False]))
1880
+ res = obj.get_result()
1881
+ assert len(res) == 2
1882
+ # Results should be right-justified.
1883
+ assert res[0] == " True"
1884
+ assert res[1] == " False"
1885
+
1886
+ def test_2d_array(self):
1887
+ obj = fmt._GenericArrayFormatter(np.array([[True, False], [False, True]]))
1888
+ res = obj.get_result()
1889
+ assert len(res) == 2
1890
+ assert res[0] == " [True, False]"
1891
+ assert res[1] == " [False, True]"
1892
+
1893
+ def test_3d_array(self):
1894
+ obj = fmt._GenericArrayFormatter(
1895
+ np.array([[[True, True], [False, False]], [[False, True], [True, False]]])
1896
+ )
1897
+ res = obj.get_result()
1898
+ assert len(res) == 2
1899
+ assert res[0] == " [[True, True], [False, False]]"
1900
+ assert res[1] == " [[False, True], [True, False]]"
1901
+
1902
+ def test_2d_extension_type(self):
1903
+ # GH 33770
1904
+
1905
+ # Define a stub extension type with just enough code to run Series.__repr__()
1906
+ class DtypeStub(pd.api.extensions.ExtensionDtype):
1907
+ @property
1908
+ def type(self):
1909
+ return np.ndarray
1910
+
1911
+ @property
1912
+ def name(self):
1913
+ return "DtypeStub"
1914
+
1915
+ class ExtTypeStub(pd.api.extensions.ExtensionArray):
1916
+ def __len__(self) -> int:
1917
+ return 2
1918
+
1919
+ def __getitem__(self, ix):
1920
+ return [ix == 1, ix == 0]
1921
+
1922
+ @property
1923
+ def dtype(self):
1924
+ return DtypeStub()
1925
+
1926
+ series = Series(ExtTypeStub(), copy=False)
1927
+ res = repr(series) # This line crashed before #33770 was fixed.
1928
+ expected = "\n".join(
1929
+ ["0 [False True]", "1 [True False]", "dtype: DtypeStub"]
1930
+ )
1931
+ assert res == expected
1932
+
1933
+
1934
+ def _three_digit_exp():
1935
+ return f"{1.7e8:.4g}" == "1.7e+008"
1936
+
1937
+
1938
+ class TestFloatArrayFormatter:
1939
+ def test_misc(self):
1940
+ obj = fmt.FloatArrayFormatter(np.array([], dtype=np.float64))
1941
+ result = obj.get_result()
1942
+ assert len(result) == 0
1943
+
1944
+ def test_format(self):
1945
+ obj = fmt.FloatArrayFormatter(np.array([12, 0], dtype=np.float64))
1946
+ result = obj.get_result()
1947
+ assert result[0] == " 12.0"
1948
+ assert result[1] == " 0.0"
1949
+
1950
+ def test_output_display_precision_trailing_zeroes(self):
1951
+ # Issue #20359: trimming zeros while there is no decimal point
1952
+
1953
+ # Happens when display precision is set to zero
1954
+ with option_context("display.precision", 0):
1955
+ s = Series([840.0, 4200.0])
1956
+ expected_output = "0 840\n1 4200\ndtype: float64"
1957
+ assert str(s) == expected_output
1958
+
1959
+ @pytest.mark.parametrize(
1960
+ "value,expected",
1961
+ [
1962
+ ([9.4444], " 0\n0 9"),
1963
+ ([0.49], " 0\n0 5e-01"),
1964
+ ([10.9999], " 0\n0 11"),
1965
+ ([9.5444, 9.6], " 0\n0 10\n1 10"),
1966
+ ([0.46, 0.78, -9.9999], " 0\n0 5e-01\n1 8e-01\n2 -1e+01"),
1967
+ ],
1968
+ )
1969
+ def test_set_option_precision(self, value, expected):
1970
+ # Issue #30122
1971
+ # Precision was incorrectly shown
1972
+
1973
+ with option_context("display.precision", 0):
1974
+ df_value = DataFrame(value)
1975
+ assert str(df_value) == expected
1976
+
1977
+ def test_output_significant_digits(self):
1978
+ # Issue #9764
1979
+
1980
+ # In case default display precision changes:
1981
+ with option_context("display.precision", 6):
1982
+ # DataFrame example from issue #9764
1983
+ d = DataFrame(
1984
+ {
1985
+ "col1": [
1986
+ 9.999e-8,
1987
+ 1e-7,
1988
+ 1.0001e-7,
1989
+ 2e-7,
1990
+ 4.999e-7,
1991
+ 5e-7,
1992
+ 5.0001e-7,
1993
+ 6e-7,
1994
+ 9.999e-7,
1995
+ 1e-6,
1996
+ 1.0001e-6,
1997
+ 2e-6,
1998
+ 4.999e-6,
1999
+ 5e-6,
2000
+ 5.0001e-6,
2001
+ 6e-6,
2002
+ ]
2003
+ }
2004
+ )
2005
+
2006
+ expected_output = {
2007
+ (0, 6): " col1\n"
2008
+ "0 9.999000e-08\n"
2009
+ "1 1.000000e-07\n"
2010
+ "2 1.000100e-07\n"
2011
+ "3 2.000000e-07\n"
2012
+ "4 4.999000e-07\n"
2013
+ "5 5.000000e-07",
2014
+ (1, 6): " col1\n"
2015
+ "1 1.000000e-07\n"
2016
+ "2 1.000100e-07\n"
2017
+ "3 2.000000e-07\n"
2018
+ "4 4.999000e-07\n"
2019
+ "5 5.000000e-07",
2020
+ (1, 8): " col1\n"
2021
+ "1 1.000000e-07\n"
2022
+ "2 1.000100e-07\n"
2023
+ "3 2.000000e-07\n"
2024
+ "4 4.999000e-07\n"
2025
+ "5 5.000000e-07\n"
2026
+ "6 5.000100e-07\n"
2027
+ "7 6.000000e-07",
2028
+ (8, 16): " col1\n"
2029
+ "8 9.999000e-07\n"
2030
+ "9 1.000000e-06\n"
2031
+ "10 1.000100e-06\n"
2032
+ "11 2.000000e-06\n"
2033
+ "12 4.999000e-06\n"
2034
+ "13 5.000000e-06\n"
2035
+ "14 5.000100e-06\n"
2036
+ "15 6.000000e-06",
2037
+ (9, 16): " col1\n"
2038
+ "9 0.000001\n"
2039
+ "10 0.000001\n"
2040
+ "11 0.000002\n"
2041
+ "12 0.000005\n"
2042
+ "13 0.000005\n"
2043
+ "14 0.000005\n"
2044
+ "15 0.000006",
2045
+ }
2046
+
2047
+ for (start, stop), v in expected_output.items():
2048
+ assert str(d[start:stop]) == v
2049
+
2050
+ def test_too_long(self):
2051
+ # GH 10451
2052
+ with option_context("display.precision", 4):
2053
+ # need both a number > 1e6 and something that normally formats to
2054
+ # having length > display.precision + 6
2055
+ df = DataFrame({"x": [12345.6789]})
2056
+ assert str(df) == " x\n0 12345.6789"
2057
+ df = DataFrame({"x": [2e6]})
2058
+ assert str(df) == " x\n0 2000000.0"
2059
+ df = DataFrame({"x": [12345.6789, 2e6]})
2060
+ assert str(df) == " x\n0 1.2346e+04\n1 2.0000e+06"
2061
+
2062
+
2063
+ class TestTimedelta64Formatter:
2064
+ def test_days(self):
2065
+ x = pd.to_timedelta(list(range(5)) + [NaT], unit="D")._values
2066
+ result = fmt._Timedelta64Formatter(x).get_result()
2067
+ assert result[0].strip() == "0 days"
2068
+ assert result[1].strip() == "1 days"
2069
+
2070
+ result = fmt._Timedelta64Formatter(x[1:2]).get_result()
2071
+ assert result[0].strip() == "1 days"
2072
+
2073
+ result = fmt._Timedelta64Formatter(x).get_result()
2074
+ assert result[0].strip() == "0 days"
2075
+ assert result[1].strip() == "1 days"
2076
+
2077
+ result = fmt._Timedelta64Formatter(x[1:2]).get_result()
2078
+ assert result[0].strip() == "1 days"
2079
+
2080
+ def test_days_neg(self):
2081
+ x = pd.to_timedelta(list(range(5)) + [NaT], unit="D")._values
2082
+ result = fmt._Timedelta64Formatter(-x).get_result()
2083
+ assert result[0].strip() == "0 days"
2084
+ assert result[1].strip() == "-1 days"
2085
+
2086
+ def test_subdays(self):
2087
+ y = pd.to_timedelta(list(range(5)) + [NaT], unit="s")._values
2088
+ result = fmt._Timedelta64Formatter(y).get_result()
2089
+ assert result[0].strip() == "0 days 00:00:00"
2090
+ assert result[1].strip() == "0 days 00:00:01"
2091
+
2092
+ def test_subdays_neg(self):
2093
+ y = pd.to_timedelta(list(range(5)) + [NaT], unit="s")._values
2094
+ result = fmt._Timedelta64Formatter(-y).get_result()
2095
+ assert result[0].strip() == "0 days 00:00:00"
2096
+ assert result[1].strip() == "-1 days +23:59:59"
2097
+
2098
+ def test_zero(self):
2099
+ x = pd.to_timedelta(list(range(1)) + [NaT], unit="D")._values
2100
+ result = fmt._Timedelta64Formatter(x).get_result()
2101
+ assert result[0].strip() == "0 days"
2102
+
2103
+ x = pd.to_timedelta(list(range(1)), unit="D")._values
2104
+ result = fmt._Timedelta64Formatter(x).get_result()
2105
+ assert result[0].strip() == "0 days"
2106
+
2107
+
2108
+ class TestDatetime64Formatter:
2109
+ def test_mixed(self):
2110
+ x = Series([datetime(2013, 1, 1), datetime(2013, 1, 1, 12), NaT])._values
2111
+ result = fmt._Datetime64Formatter(x).get_result()
2112
+ assert result[0].strip() == "2013-01-01 00:00:00"
2113
+ assert result[1].strip() == "2013-01-01 12:00:00"
2114
+
2115
+ def test_dates(self):
2116
+ x = Series([datetime(2013, 1, 1), datetime(2013, 1, 2), NaT])._values
2117
+ result = fmt._Datetime64Formatter(x).get_result()
2118
+ assert result[0].strip() == "2013-01-01"
2119
+ assert result[1].strip() == "2013-01-02"
2120
+
2121
+ def test_date_nanos(self):
2122
+ x = Series([Timestamp(200)])._values
2123
+ result = fmt._Datetime64Formatter(x).get_result()
2124
+ assert result[0].strip() == "1970-01-01 00:00:00.000000200"
2125
+
2126
+ def test_dates_display(self):
2127
+ # 10170
2128
+ # make sure that we are consistently display date formatting
2129
+ x = Series(date_range("20130101 09:00:00", periods=5, freq="D"))
2130
+ x.iloc[1] = np.nan
2131
+ result = fmt._Datetime64Formatter(x._values).get_result()
2132
+ assert result[0].strip() == "2013-01-01 09:00:00"
2133
+ assert result[1].strip() == "NaT"
2134
+ assert result[4].strip() == "2013-01-05 09:00:00"
2135
+
2136
+ x = Series(date_range("20130101 09:00:00", periods=5, freq="s"))
2137
+ x.iloc[1] = np.nan
2138
+ result = fmt._Datetime64Formatter(x._values).get_result()
2139
+ assert result[0].strip() == "2013-01-01 09:00:00"
2140
+ assert result[1].strip() == "NaT"
2141
+ assert result[4].strip() == "2013-01-01 09:00:04"
2142
+
2143
+ x = Series(date_range("20130101 09:00:00", periods=5, freq="ms"))
2144
+ x.iloc[1] = np.nan
2145
+ result = fmt._Datetime64Formatter(x._values).get_result()
2146
+ assert result[0].strip() == "2013-01-01 09:00:00.000"
2147
+ assert result[1].strip() == "NaT"
2148
+ assert result[4].strip() == "2013-01-01 09:00:00.004"
2149
+
2150
+ x = Series(date_range("20130101 09:00:00", periods=5, freq="us"))
2151
+ x.iloc[1] = np.nan
2152
+ result = fmt._Datetime64Formatter(x._values).get_result()
2153
+ assert result[0].strip() == "2013-01-01 09:00:00.000000"
2154
+ assert result[1].strip() == "NaT"
2155
+ assert result[4].strip() == "2013-01-01 09:00:00.000004"
2156
+
2157
+ x = Series(date_range("20130101 09:00:00", periods=5, freq="ns"))
2158
+ x.iloc[1] = np.nan
2159
+ result = fmt._Datetime64Formatter(x._values).get_result()
2160
+ assert result[0].strip() == "2013-01-01 09:00:00.000000000"
2161
+ assert result[1].strip() == "NaT"
2162
+ assert result[4].strip() == "2013-01-01 09:00:00.000000004"
2163
+
2164
+ def test_datetime64formatter_yearmonth(self):
2165
+ x = Series([datetime(2016, 1, 1), datetime(2016, 2, 2)])._values
2166
+
2167
+ def format_func(x):
2168
+ return x.strftime("%Y-%m")
2169
+
2170
+ formatter = fmt._Datetime64Formatter(x, formatter=format_func)
2171
+ result = formatter.get_result()
2172
+ assert result == ["2016-01", "2016-02"]
2173
+
2174
+ def test_datetime64formatter_hoursecond(self):
2175
+ x = Series(
2176
+ pd.to_datetime(["10:10:10.100", "12:12:12.120"], format="%H:%M:%S.%f")
2177
+ )._values
2178
+
2179
+ def format_func(x):
2180
+ return x.strftime("%H:%M")
2181
+
2182
+ formatter = fmt._Datetime64Formatter(x, formatter=format_func)
2183
+ result = formatter.get_result()
2184
+ assert result == ["10:10", "12:12"]
2185
+
2186
+ def test_datetime64formatter_tz_ms(self):
2187
+ x = (
2188
+ Series(
2189
+ np.array(["2999-01-01", "2999-01-02", "NaT"], dtype="datetime64[ms]")
2190
+ )
2191
+ .dt.tz_localize("US/Pacific")
2192
+ ._values
2193
+ )
2194
+ result = fmt._Datetime64TZFormatter(x).get_result()
2195
+ assert result[0].strip() == "2999-01-01 00:00:00-08:00"
2196
+ assert result[1].strip() == "2999-01-02 00:00:00-08:00"
2197
+
2198
+
2199
+ class TestFormatPercentiles:
2200
+ @pytest.mark.parametrize(
2201
+ "percentiles, expected",
2202
+ [
2203
+ (
2204
+ [0.01999, 0.02001, 0.5, 0.666666, 0.9999],
2205
+ ["1.999%", "2.001%", "50%", "66.667%", "99.99%"],
2206
+ ),
2207
+ (
2208
+ [0, 0.5, 0.02001, 0.5, 0.666666, 0.9999],
2209
+ ["0%", "50%", "2.0%", "50%", "66.67%", "99.99%"],
2210
+ ),
2211
+ ([0.281, 0.29, 0.57, 0.58], ["28.1%", "29%", "57%", "58%"]),
2212
+ ([0.28, 0.29, 0.57, 0.58], ["28%", "29%", "57%", "58%"]),
2213
+ (
2214
+ [0.9, 0.99, 0.999, 0.9999, 0.99999],
2215
+ ["90%", "99%", "99.9%", "99.99%", "99.999%"],
2216
+ ),
2217
+ ],
2218
+ )
2219
+ def test_format_percentiles(self, percentiles, expected):
2220
+ result = fmt.format_percentiles(percentiles)
2221
+ assert result == expected
2222
+
2223
+ @pytest.mark.parametrize(
2224
+ "percentiles",
2225
+ [
2226
+ ([0.1, np.nan, 0.5]),
2227
+ ([-0.001, 0.1, 0.5]),
2228
+ ([2, 0.1, 0.5]),
2229
+ ([0.1, 0.5, "a"]),
2230
+ ],
2231
+ )
2232
+ def test_error_format_percentiles(self, percentiles):
2233
+ msg = r"percentiles should all be in the interval \[0,1\]"
2234
+ with pytest.raises(ValueError, match=msg):
2235
+ fmt.format_percentiles(percentiles)
2236
+
2237
+ def test_format_percentiles_integer_idx(self):
2238
+ # Issue #26660
2239
+ result = fmt.format_percentiles(np.linspace(0, 1, 10 + 1))
2240
+ expected = [
2241
+ "0%",
2242
+ "10%",
2243
+ "20%",
2244
+ "30%",
2245
+ "40%",
2246
+ "50%",
2247
+ "60%",
2248
+ "70%",
2249
+ "80%",
2250
+ "90%",
2251
+ "100%",
2252
+ ]
2253
+ assert result == expected
2254
+
2255
+
2256
+ @pytest.mark.parametrize("method", ["to_string", "to_html", "to_latex"])
2257
+ @pytest.mark.parametrize(
2258
+ "encoding, data",
2259
+ [(None, "abc"), ("utf-8", "abc"), ("gbk", "ι€ ζˆθΎ“ε‡ΊδΈ­ζ–‡ζ˜Ύη€ΊδΉ±η "), ("foo", "abc")],
2260
+ )
2261
+ def test_filepath_or_buffer_arg(
2262
+ method,
2263
+ filepath_or_buffer,
2264
+ assert_filepath_or_buffer_equals,
2265
+ encoding,
2266
+ data,
2267
+ filepath_or_buffer_id,
2268
+ ):
2269
+ df = DataFrame([data])
2270
+ if method in ["to_latex"]: # uses styler implementation
2271
+ pytest.importorskip("jinja2")
2272
+
2273
+ if filepath_or_buffer_id not in ["string", "pathlike"] and encoding is not None:
2274
+ with pytest.raises(
2275
+ ValueError, match="buf is not a file name and encoding is specified."
2276
+ ):
2277
+ getattr(df, method)(buf=filepath_or_buffer, encoding=encoding)
2278
+ elif encoding == "foo":
2279
+ with pytest.raises(LookupError, match="unknown encoding"):
2280
+ getattr(df, method)(buf=filepath_or_buffer, encoding=encoding)
2281
+ else:
2282
+ expected = getattr(df, method)()
2283
+ getattr(df, method)(buf=filepath_or_buffer, encoding=encoding)
2284
+ assert_filepath_or_buffer_equals(expected)
2285
+
2286
+
2287
+ @pytest.mark.parametrize("method", ["to_string", "to_html", "to_latex"])
2288
+ def test_filepath_or_buffer_bad_arg_raises(float_frame, method):
2289
+ if method in ["to_latex"]: # uses styler implementation
2290
+ pytest.importorskip("jinja2")
2291
+ msg = "buf is not a file name and it has no write method"
2292
+ with pytest.raises(TypeError, match=msg):
2293
+ getattr(float_frame, method)(buf=object())
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/test_ipython_compat.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ import pandas._config.config as cf
4
+
5
+ from pandas import (
6
+ DataFrame,
7
+ MultiIndex,
8
+ )
9
+
10
+
11
+ class TestTableSchemaRepr:
12
+ def test_publishes(self, ip):
13
+ ipython = ip.instance(config=ip.config)
14
+ df = DataFrame({"A": [1, 2]})
15
+ objects = [df["A"], df] # dataframe / series
16
+ expected_keys = [
17
+ {"text/plain", "application/vnd.dataresource+json"},
18
+ {"text/plain", "text/html", "application/vnd.dataresource+json"},
19
+ ]
20
+
21
+ opt = cf.option_context("display.html.table_schema", True)
22
+ last_obj = None
23
+ for obj, expected in zip(objects, expected_keys):
24
+ last_obj = obj
25
+ with opt:
26
+ formatted = ipython.display_formatter.format(obj)
27
+ assert set(formatted[0].keys()) == expected
28
+
29
+ with_latex = cf.option_context("styler.render.repr", "latex")
30
+
31
+ with opt, with_latex:
32
+ formatted = ipython.display_formatter.format(last_obj)
33
+
34
+ expected = {
35
+ "text/plain",
36
+ "text/html",
37
+ "text/latex",
38
+ "application/vnd.dataresource+json",
39
+ }
40
+ assert set(formatted[0].keys()) == expected
41
+
42
+ def test_publishes_not_implemented(self, ip):
43
+ # column MultiIndex
44
+ # GH#15996
45
+ midx = MultiIndex.from_product([["A", "B"], ["a", "b", "c"]])
46
+ df = DataFrame(
47
+ np.random.default_rng(2).standard_normal((5, len(midx))), columns=midx
48
+ )
49
+
50
+ opt = cf.option_context("display.html.table_schema", True)
51
+
52
+ with opt:
53
+ formatted = ip.instance(config=ip.config).display_formatter.format(df)
54
+
55
+ expected = {"text/plain", "text/html"}
56
+ assert set(formatted[0].keys()) == expected
57
+
58
+ def test_config_on(self):
59
+ df = DataFrame({"A": [1, 2]})
60
+ with cf.option_context("display.html.table_schema", True):
61
+ result = df._repr_data_resource_()
62
+
63
+ assert result is not None
64
+
65
+ def test_config_default_off(self):
66
+ df = DataFrame({"A": [1, 2]})
67
+ with cf.option_context("display.html.table_schema", False):
68
+ result = df._repr_data_resource_()
69
+
70
+ assert result is None
71
+
72
+ def test_enable_data_resource_formatter(self, ip):
73
+ # GH#10491
74
+ formatters = ip.instance(config=ip.config).display_formatter.formatters
75
+ mimetype = "application/vnd.dataresource+json"
76
+
77
+ with cf.option_context("display.html.table_schema", True):
78
+ assert "application/vnd.dataresource+json" in formatters
79
+ assert formatters[mimetype].enabled
80
+
81
+ # still there, just disabled
82
+ assert "application/vnd.dataresource+json" in formatters
83
+ assert not formatters[mimetype].enabled
84
+
85
+ # able to re-set
86
+ with cf.option_context("display.html.table_schema", True):
87
+ assert "application/vnd.dataresource+json" in formatters
88
+ assert formatters[mimetype].enabled
89
+ # smoke test that it works
90
+ ip.instance(config=ip.config).display_formatter.format(cf)
llmeval-env/lib/python3.10/site-packages/pandas/tests/io/formats/test_printing.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Note! This file is aimed specifically at pandas.io.formats.printing utility
2
+ # functions, not the general printing of pandas objects.
3
+ import string
4
+
5
+ import pandas._config.config as cf
6
+
7
+ from pandas.io.formats import printing
8
+
9
+
10
+ def test_adjoin():
11
+ data = [["a", "b", "c"], ["dd", "ee", "ff"], ["ggg", "hhh", "iii"]]
12
+ expected = "a dd ggg\nb ee hhh\nc ff iii"
13
+
14
+ adjoined = printing.adjoin(2, *data)
15
+
16
+ assert adjoined == expected
17
+
18
+
19
+ class TestPPrintThing:
20
+ def test_repr_binary_type(self):
21
+ letters = string.ascii_letters
22
+ try:
23
+ raw = bytes(letters, encoding=cf.get_option("display.encoding"))
24
+ except TypeError:
25
+ raw = bytes(letters)
26
+ b = str(raw.decode("utf-8"))
27
+ res = printing.pprint_thing(b, quote_strings=True)
28
+ assert res == repr(b)
29
+ res = printing.pprint_thing(b, quote_strings=False)
30
+ assert res == b
31
+
32
+ def test_repr_obeys_max_seq_limit(self):
33
+ with cf.option_context("display.max_seq_items", 2000):
34
+ assert len(printing.pprint_thing(list(range(1000)))) > 1000
35
+
36
+ with cf.option_context("display.max_seq_items", 5):
37
+ assert len(printing.pprint_thing(list(range(1000)))) < 100
38
+
39
+ with cf.option_context("display.max_seq_items", 1):
40
+ assert len(printing.pprint_thing(list(range(1000)))) < 9
41
+
42
+ def test_repr_set(self):
43
+ assert printing.pprint_thing({1}) == "{1}"
44
+
45
+
46
+ class TestFormatBase:
47
+ def test_adjoin(self):
48
+ data = [["a", "b", "c"], ["dd", "ee", "ff"], ["ggg", "hhh", "iii"]]
49
+ expected = "a dd ggg\nb ee hhh\nc ff iii"
50
+
51
+ adjoined = printing.adjoin(2, *data)
52
+
53
+ assert adjoined == expected
54
+
55
+ def test_adjoin_unicode(self):
56
+ data = [["あ", "b", "c"], ["dd", "ええ", "ff"], ["ggg", "hhh", "いいい"]]
57
+ expected = "あ dd ggg\nb ええ hhh\nc ff いいい"
58
+ adjoined = printing.adjoin(2, *data)
59
+ assert adjoined == expected
60
+
61
+ adj = printing._EastAsianTextAdjustment()
62
+
63
+ expected = """あ dd ggg
64
+ b ええ hhh
65
+ c ff いいい"""
66
+
67
+ adjoined = adj.adjoin(2, *data)
68
+ assert adjoined == expected
69
+ cols = adjoined.split("\n")
70
+ assert adj.len(cols[0]) == 13
71
+ assert adj.len(cols[1]) == 13
72
+ assert adj.len(cols[2]) == 16
73
+
74
+ expected = """あ dd ggg
75
+ b ええ hhh
76
+ c ff いいい"""
77
+
78
+ adjoined = adj.adjoin(7, *data)
79
+ assert adjoined == expected
80
+ cols = adjoined.split("\n")
81
+ assert adj.len(cols[0]) == 23
82
+ assert adj.len(cols[1]) == 23
83
+ assert adj.len(cols[2]) == 26
84
+
85
+ def test_justify(self):
86
+ adj = printing._EastAsianTextAdjustment()
87
+
88
+ def just(x, *args, **kwargs):
89
+ # wrapper to test single str
90
+ return adj.justify([x], *args, **kwargs)[0]
91
+
92
+ assert just("abc", 5, mode="left") == "abc "
93
+ assert just("abc", 5, mode="center") == " abc "
94
+ assert just("abc", 5, mode="right") == " abc"
95
+ assert just("abc", 5, mode="left") == "abc "
96
+ assert just("abc", 5, mode="center") == " abc "
97
+ assert just("abc", 5, mode="right") == " abc"
98
+
99
+ assert just("パンダ", 5, mode="left") == "パンダ"
100
+ assert just("パンダ", 5, mode="center") == "パンダ"
101
+ assert just("パンダ", 5, mode="right") == "パンダ"
102
+
103
+ assert just("パンダ", 10, mode="left") == "パンダ "
104
+ assert just("パンダ", 10, mode="center") == " パンダ "
105
+ assert just("パンダ", 10, mode="right") == " パンダ"
106
+
107
+ def test_east_asian_len(self):
108
+ adj = printing._EastAsianTextAdjustment()
109
+
110
+ assert adj.len("abc") == 3
111
+ assert adj.len("abc") == 3
112
+
113
+ assert adj.len("パンダ") == 6
114
+ assert adj.len("οΎŠοΎŸοΎοΎ€οΎž") == 5
115
+ assert adj.len("パンダpanda") == 11
116
+ assert adj.len("οΎŠοΎŸοΎοΎ€οΎžpanda") == 10
117
+
118
+ def test_ambiguous_width(self):
119
+ adj = printing._EastAsianTextAdjustment()
120
+ assert adj.len("‘‘ab") == 4
121
+
122
+ with cf.option_context("display.unicode.ambiguous_as_wide", True):
123
+ adj = printing._EastAsianTextAdjustment()
124
+ assert adj.len("‘‘ab") == 6
125
+
126
+ data = [["あ", "b", "c"], ["dd", "ええ", "ff"], ["ggg", "‘‘ab", "いいい"]]
127
+ expected = "あ dd ggg \nb ええ ‘‘ab\nc ff いいい"
128
+ adjoined = adj.adjoin(2, *data)
129
+ assert adjoined == expected