Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- ckpts/llama-3b/global_step100/bf16_zero_pp_rank_183_mp_rank_03_optim_states.pt +3 -0
- venv/lib/python3.10/site-packages/pandas/tests/api/__init__.py +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/api/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/api/__pycache__/test_api.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/api/__pycache__/test_types.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/api/test_api.py +383 -0
- venv/lib/python3.10/site-packages/pandas/tests/api/test_types.py +62 -0
- venv/lib/python3.10/site-packages/pandas/tests/arrays/sparse/__pycache__/test_astype.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/arrays/sparse/__pycache__/test_combine_concat.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/arrays/sparse/__pycache__/test_reductions.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/arrays/sparse/__pycache__/test_unary.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/__init__.py +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_console.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_css.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_eng_formatting.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_format.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_ipython_compat.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_printing.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_to_csv.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_to_excel.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_to_html.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_to_latex.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_to_markdown.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_to_string.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/__init__.py +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_bar.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_exceptions.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_format.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_highlight.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_html.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_matplotlib.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_non_unique.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_style.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_to_latex.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_to_string.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_tooltip.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/test_bar.py +358 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/test_exceptions.py +44 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/test_format.py +562 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/test_highlight.py +218 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/test_html.py +1009 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/test_matplotlib.py +335 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/test_non_unique.py +140 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/test_style.py +1588 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/test_to_latex.py +1090 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/test_to_string.py +96 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/test_tooltip.py +85 -0
- venv/lib/python3.10/site-packages/pandas/tests/io/formats/test_css.py +289 -0
ckpts/llama-3b/global_step100/bf16_zero_pp_rank_183_mp_rank_03_optim_states.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:2f446402ba72c4e2c94858ef15fbd6f5e2593674bd5e04ca2367f5ba80774d84
|
3 |
+
size 41830404
|
venv/lib/python3.10/site-packages/pandas/tests/api/__init__.py
ADDED
File without changes
|
venv/lib/python3.10/site-packages/pandas/tests/api/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (184 Bytes). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/api/__pycache__/test_api.cpython-310.pyc
ADDED
Binary file (7.85 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/api/__pycache__/test_types.cpython-310.pyc
ADDED
Binary file (1.89 kB). View file
|
|
venv/lib/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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
import pytest
|
4 |
+
|
5 |
+
import pandas as pd
|
6 |
+
from pandas import api
|
7 |
+
import pandas._testing as tm
|
8 |
+
from pandas.api import (
|
9 |
+
extensions as api_extensions,
|
10 |
+
indexers as api_indexers,
|
11 |
+
interchange as api_interchange,
|
12 |
+
types as api_types,
|
13 |
+
typing as api_typing,
|
14 |
+
)
|
15 |
+
|
16 |
+
|
17 |
+
class Base:
|
18 |
+
def check(self, namespace, expected, ignored=None):
|
19 |
+
# see which names are in the namespace, minus optional
|
20 |
+
# ignored ones
|
21 |
+
# compare vs the expected
|
22 |
+
|
23 |
+
result = sorted(
|
24 |
+
f for f in dir(namespace) if not f.startswith("__") and f != "annotations"
|
25 |
+
)
|
26 |
+
if ignored is not None:
|
27 |
+
result = sorted(set(result) - set(ignored))
|
28 |
+
|
29 |
+
expected = sorted(expected)
|
30 |
+
tm.assert_almost_equal(result, expected)
|
31 |
+
|
32 |
+
|
33 |
+
class TestPDApi(Base):
|
34 |
+
# these are optionally imported based on testing
|
35 |
+
# & need to be ignored
|
36 |
+
ignored = ["tests", "locale", "conftest", "_version_meson"]
|
37 |
+
|
38 |
+
# top-level sub-packages
|
39 |
+
public_lib = [
|
40 |
+
"api",
|
41 |
+
"arrays",
|
42 |
+
"options",
|
43 |
+
"test",
|
44 |
+
"testing",
|
45 |
+
"errors",
|
46 |
+
"plotting",
|
47 |
+
"io",
|
48 |
+
"tseries",
|
49 |
+
]
|
50 |
+
private_lib = ["compat", "core", "pandas", "util", "_built_with_meson"]
|
51 |
+
|
52 |
+
# misc
|
53 |
+
misc = ["IndexSlice", "NaT", "NA"]
|
54 |
+
|
55 |
+
# top-level classes
|
56 |
+
classes = [
|
57 |
+
"ArrowDtype",
|
58 |
+
"Categorical",
|
59 |
+
"CategoricalIndex",
|
60 |
+
"DataFrame",
|
61 |
+
"DateOffset",
|
62 |
+
"DatetimeIndex",
|
63 |
+
"ExcelFile",
|
64 |
+
"ExcelWriter",
|
65 |
+
"Flags",
|
66 |
+
"Grouper",
|
67 |
+
"HDFStore",
|
68 |
+
"Index",
|
69 |
+
"MultiIndex",
|
70 |
+
"Period",
|
71 |
+
"PeriodIndex",
|
72 |
+
"RangeIndex",
|
73 |
+
"Series",
|
74 |
+
"SparseDtype",
|
75 |
+
"StringDtype",
|
76 |
+
"Timedelta",
|
77 |
+
"TimedeltaIndex",
|
78 |
+
"Timestamp",
|
79 |
+
"Interval",
|
80 |
+
"IntervalIndex",
|
81 |
+
"CategoricalDtype",
|
82 |
+
"PeriodDtype",
|
83 |
+
"IntervalDtype",
|
84 |
+
"DatetimeTZDtype",
|
85 |
+
"BooleanDtype",
|
86 |
+
"Int8Dtype",
|
87 |
+
"Int16Dtype",
|
88 |
+
"Int32Dtype",
|
89 |
+
"Int64Dtype",
|
90 |
+
"UInt8Dtype",
|
91 |
+
"UInt16Dtype",
|
92 |
+
"UInt32Dtype",
|
93 |
+
"UInt64Dtype",
|
94 |
+
"Float32Dtype",
|
95 |
+
"Float64Dtype",
|
96 |
+
"NamedAgg",
|
97 |
+
]
|
98 |
+
|
99 |
+
# these are already deprecated; awaiting removal
|
100 |
+
deprecated_classes: list[str] = []
|
101 |
+
|
102 |
+
# external modules exposed in pandas namespace
|
103 |
+
modules: list[str] = []
|
104 |
+
|
105 |
+
# top-level functions
|
106 |
+
funcs = [
|
107 |
+
"array",
|
108 |
+
"bdate_range",
|
109 |
+
"concat",
|
110 |
+
"crosstab",
|
111 |
+
"cut",
|
112 |
+
"date_range",
|
113 |
+
"interval_range",
|
114 |
+
"eval",
|
115 |
+
"factorize",
|
116 |
+
"get_dummies",
|
117 |
+
"from_dummies",
|
118 |
+
"infer_freq",
|
119 |
+
"isna",
|
120 |
+
"isnull",
|
121 |
+
"lreshape",
|
122 |
+
"melt",
|
123 |
+
"notna",
|
124 |
+
"notnull",
|
125 |
+
"offsets",
|
126 |
+
"merge",
|
127 |
+
"merge_ordered",
|
128 |
+
"merge_asof",
|
129 |
+
"period_range",
|
130 |
+
"pivot",
|
131 |
+
"pivot_table",
|
132 |
+
"qcut",
|
133 |
+
"show_versions",
|
134 |
+
"timedelta_range",
|
135 |
+
"unique",
|
136 |
+
"value_counts",
|
137 |
+
"wide_to_long",
|
138 |
+
]
|
139 |
+
|
140 |
+
# top-level option funcs
|
141 |
+
funcs_option = [
|
142 |
+
"reset_option",
|
143 |
+
"describe_option",
|
144 |
+
"get_option",
|
145 |
+
"option_context",
|
146 |
+
"set_option",
|
147 |
+
"set_eng_float_format",
|
148 |
+
]
|
149 |
+
|
150 |
+
# top-level read_* funcs
|
151 |
+
funcs_read = [
|
152 |
+
"read_clipboard",
|
153 |
+
"read_csv",
|
154 |
+
"read_excel",
|
155 |
+
"read_fwf",
|
156 |
+
"read_gbq",
|
157 |
+
"read_hdf",
|
158 |
+
"read_html",
|
159 |
+
"read_xml",
|
160 |
+
"read_json",
|
161 |
+
"read_pickle",
|
162 |
+
"read_sas",
|
163 |
+
"read_sql",
|
164 |
+
"read_sql_query",
|
165 |
+
"read_sql_table",
|
166 |
+
"read_stata",
|
167 |
+
"read_table",
|
168 |
+
"read_feather",
|
169 |
+
"read_parquet",
|
170 |
+
"read_orc",
|
171 |
+
"read_spss",
|
172 |
+
]
|
173 |
+
|
174 |
+
# top-level json funcs
|
175 |
+
funcs_json = ["json_normalize"]
|
176 |
+
|
177 |
+
# top-level to_* funcs
|
178 |
+
funcs_to = ["to_datetime", "to_numeric", "to_pickle", "to_timedelta"]
|
179 |
+
|
180 |
+
# top-level to deprecate in the future
|
181 |
+
deprecated_funcs_in_future: list[str] = []
|
182 |
+
|
183 |
+
# these are already deprecated; awaiting removal
|
184 |
+
deprecated_funcs: list[str] = []
|
185 |
+
|
186 |
+
# private modules in pandas namespace
|
187 |
+
private_modules = [
|
188 |
+
"_config",
|
189 |
+
"_libs",
|
190 |
+
"_is_numpy_dev",
|
191 |
+
"_pandas_datetime_CAPI",
|
192 |
+
"_pandas_parser_CAPI",
|
193 |
+
"_testing",
|
194 |
+
"_typing",
|
195 |
+
]
|
196 |
+
if not pd._built_with_meson:
|
197 |
+
private_modules.append("_version")
|
198 |
+
|
199 |
+
def test_api(self):
|
200 |
+
checkthese = (
|
201 |
+
self.public_lib
|
202 |
+
+ self.private_lib
|
203 |
+
+ self.misc
|
204 |
+
+ self.modules
|
205 |
+
+ self.classes
|
206 |
+
+ self.funcs
|
207 |
+
+ self.funcs_option
|
208 |
+
+ self.funcs_read
|
209 |
+
+ self.funcs_json
|
210 |
+
+ self.funcs_to
|
211 |
+
+ self.private_modules
|
212 |
+
)
|
213 |
+
self.check(namespace=pd, expected=checkthese, ignored=self.ignored)
|
214 |
+
|
215 |
+
def test_api_all(self):
|
216 |
+
expected = set(
|
217 |
+
self.public_lib
|
218 |
+
+ self.misc
|
219 |
+
+ self.modules
|
220 |
+
+ self.classes
|
221 |
+
+ self.funcs
|
222 |
+
+ self.funcs_option
|
223 |
+
+ self.funcs_read
|
224 |
+
+ self.funcs_json
|
225 |
+
+ self.funcs_to
|
226 |
+
) - set(self.deprecated_classes)
|
227 |
+
actual = set(pd.__all__)
|
228 |
+
|
229 |
+
extraneous = actual - expected
|
230 |
+
assert not extraneous
|
231 |
+
|
232 |
+
missing = expected - actual
|
233 |
+
assert not missing
|
234 |
+
|
235 |
+
def test_depr(self):
|
236 |
+
deprecated_list = (
|
237 |
+
self.deprecated_classes
|
238 |
+
+ self.deprecated_funcs
|
239 |
+
+ self.deprecated_funcs_in_future
|
240 |
+
)
|
241 |
+
for depr in deprecated_list:
|
242 |
+
with tm.assert_produces_warning(FutureWarning):
|
243 |
+
_ = getattr(pd, depr)
|
244 |
+
|
245 |
+
|
246 |
+
class TestApi(Base):
|
247 |
+
allowed_api_dirs = [
|
248 |
+
"types",
|
249 |
+
"extensions",
|
250 |
+
"indexers",
|
251 |
+
"interchange",
|
252 |
+
"typing",
|
253 |
+
]
|
254 |
+
allowed_typing = [
|
255 |
+
"DataFrameGroupBy",
|
256 |
+
"DatetimeIndexResamplerGroupby",
|
257 |
+
"Expanding",
|
258 |
+
"ExpandingGroupby",
|
259 |
+
"ExponentialMovingWindow",
|
260 |
+
"ExponentialMovingWindowGroupby",
|
261 |
+
"JsonReader",
|
262 |
+
"NaTType",
|
263 |
+
"NAType",
|
264 |
+
"PeriodIndexResamplerGroupby",
|
265 |
+
"Resampler",
|
266 |
+
"Rolling",
|
267 |
+
"RollingGroupby",
|
268 |
+
"SeriesGroupBy",
|
269 |
+
"StataReader",
|
270 |
+
"TimedeltaIndexResamplerGroupby",
|
271 |
+
"TimeGrouper",
|
272 |
+
"Window",
|
273 |
+
]
|
274 |
+
allowed_api_types = [
|
275 |
+
"is_any_real_numeric_dtype",
|
276 |
+
"is_array_like",
|
277 |
+
"is_bool",
|
278 |
+
"is_bool_dtype",
|
279 |
+
"is_categorical_dtype",
|
280 |
+
"is_complex",
|
281 |
+
"is_complex_dtype",
|
282 |
+
"is_datetime64_any_dtype",
|
283 |
+
"is_datetime64_dtype",
|
284 |
+
"is_datetime64_ns_dtype",
|
285 |
+
"is_datetime64tz_dtype",
|
286 |
+
"is_dict_like",
|
287 |
+
"is_dtype_equal",
|
288 |
+
"is_extension_array_dtype",
|
289 |
+
"is_file_like",
|
290 |
+
"is_float",
|
291 |
+
"is_float_dtype",
|
292 |
+
"is_hashable",
|
293 |
+
"is_int64_dtype",
|
294 |
+
"is_integer",
|
295 |
+
"is_integer_dtype",
|
296 |
+
"is_interval",
|
297 |
+
"is_interval_dtype",
|
298 |
+
"is_iterator",
|
299 |
+
"is_list_like",
|
300 |
+
"is_named_tuple",
|
301 |
+
"is_number",
|
302 |
+
"is_numeric_dtype",
|
303 |
+
"is_object_dtype",
|
304 |
+
"is_period_dtype",
|
305 |
+
"is_re",
|
306 |
+
"is_re_compilable",
|
307 |
+
"is_scalar",
|
308 |
+
"is_signed_integer_dtype",
|
309 |
+
"is_sparse",
|
310 |
+
"is_string_dtype",
|
311 |
+
"is_timedelta64_dtype",
|
312 |
+
"is_timedelta64_ns_dtype",
|
313 |
+
"is_unsigned_integer_dtype",
|
314 |
+
"pandas_dtype",
|
315 |
+
"infer_dtype",
|
316 |
+
"union_categoricals",
|
317 |
+
"CategoricalDtype",
|
318 |
+
"DatetimeTZDtype",
|
319 |
+
"IntervalDtype",
|
320 |
+
"PeriodDtype",
|
321 |
+
]
|
322 |
+
allowed_api_interchange = ["from_dataframe", "DataFrame"]
|
323 |
+
allowed_api_indexers = [
|
324 |
+
"check_array_indexer",
|
325 |
+
"BaseIndexer",
|
326 |
+
"FixedForwardWindowIndexer",
|
327 |
+
"VariableOffsetWindowIndexer",
|
328 |
+
]
|
329 |
+
allowed_api_extensions = [
|
330 |
+
"no_default",
|
331 |
+
"ExtensionDtype",
|
332 |
+
"register_extension_dtype",
|
333 |
+
"register_dataframe_accessor",
|
334 |
+
"register_index_accessor",
|
335 |
+
"register_series_accessor",
|
336 |
+
"take",
|
337 |
+
"ExtensionArray",
|
338 |
+
"ExtensionScalarOpsMixin",
|
339 |
+
]
|
340 |
+
|
341 |
+
def test_api(self):
|
342 |
+
self.check(api, self.allowed_api_dirs)
|
343 |
+
|
344 |
+
def test_api_typing(self):
|
345 |
+
self.check(api_typing, self.allowed_typing)
|
346 |
+
|
347 |
+
def test_api_types(self):
|
348 |
+
self.check(api_types, self.allowed_api_types)
|
349 |
+
|
350 |
+
def test_api_interchange(self):
|
351 |
+
self.check(api_interchange, self.allowed_api_interchange)
|
352 |
+
|
353 |
+
def test_api_indexers(self):
|
354 |
+
self.check(api_indexers, self.allowed_api_indexers)
|
355 |
+
|
356 |
+
def test_api_extensions(self):
|
357 |
+
self.check(api_extensions, self.allowed_api_extensions)
|
358 |
+
|
359 |
+
|
360 |
+
class TestTesting(Base):
|
361 |
+
funcs = [
|
362 |
+
"assert_frame_equal",
|
363 |
+
"assert_series_equal",
|
364 |
+
"assert_index_equal",
|
365 |
+
"assert_extension_array_equal",
|
366 |
+
]
|
367 |
+
|
368 |
+
def test_testing(self):
|
369 |
+
from pandas import testing
|
370 |
+
|
371 |
+
self.check(testing, self.funcs)
|
372 |
+
|
373 |
+
def test_util_in_top_level(self):
|
374 |
+
with pytest.raises(AttributeError, match="foo"):
|
375 |
+
pd.util.foo
|
376 |
+
|
377 |
+
|
378 |
+
def test_pandas_array_alias():
|
379 |
+
msg = "PandasArray has been renamed NumpyExtensionArray"
|
380 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
381 |
+
res = pd.arrays.PandasArray
|
382 |
+
|
383 |
+
assert res is pd.arrays.NumpyExtensionArray
|
venv/lib/python3.10/site-packages/pandas/tests/api/test_types.py
ADDED
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
import pandas._testing as tm
|
4 |
+
from pandas.api import types
|
5 |
+
from pandas.tests.api.test_api import Base
|
6 |
+
|
7 |
+
|
8 |
+
class TestTypes(Base):
|
9 |
+
allowed = [
|
10 |
+
"is_any_real_numeric_dtype",
|
11 |
+
"is_bool",
|
12 |
+
"is_bool_dtype",
|
13 |
+
"is_categorical_dtype",
|
14 |
+
"is_complex",
|
15 |
+
"is_complex_dtype",
|
16 |
+
"is_datetime64_any_dtype",
|
17 |
+
"is_datetime64_dtype",
|
18 |
+
"is_datetime64_ns_dtype",
|
19 |
+
"is_datetime64tz_dtype",
|
20 |
+
"is_dtype_equal",
|
21 |
+
"is_float",
|
22 |
+
"is_float_dtype",
|
23 |
+
"is_int64_dtype",
|
24 |
+
"is_integer",
|
25 |
+
"is_integer_dtype",
|
26 |
+
"is_number",
|
27 |
+
"is_numeric_dtype",
|
28 |
+
"is_object_dtype",
|
29 |
+
"is_scalar",
|
30 |
+
"is_sparse",
|
31 |
+
"is_string_dtype",
|
32 |
+
"is_signed_integer_dtype",
|
33 |
+
"is_timedelta64_dtype",
|
34 |
+
"is_timedelta64_ns_dtype",
|
35 |
+
"is_unsigned_integer_dtype",
|
36 |
+
"is_period_dtype",
|
37 |
+
"is_interval",
|
38 |
+
"is_interval_dtype",
|
39 |
+
"is_re",
|
40 |
+
"is_re_compilable",
|
41 |
+
"is_dict_like",
|
42 |
+
"is_iterator",
|
43 |
+
"is_file_like",
|
44 |
+
"is_list_like",
|
45 |
+
"is_hashable",
|
46 |
+
"is_array_like",
|
47 |
+
"is_named_tuple",
|
48 |
+
"pandas_dtype",
|
49 |
+
"union_categoricals",
|
50 |
+
"infer_dtype",
|
51 |
+
"is_extension_array_dtype",
|
52 |
+
]
|
53 |
+
deprecated: list[str] = []
|
54 |
+
dtypes = ["CategoricalDtype", "DatetimeTZDtype", "PeriodDtype", "IntervalDtype"]
|
55 |
+
|
56 |
+
def test_types(self):
|
57 |
+
self.check(types, self.allowed + self.dtypes + self.deprecated)
|
58 |
+
|
59 |
+
def test_deprecated_from_api_types(self):
|
60 |
+
for t in self.deprecated:
|
61 |
+
with tm.assert_produces_warning(FutureWarning):
|
62 |
+
getattr(types, t)(1)
|
venv/lib/python3.10/site-packages/pandas/tests/arrays/sparse/__pycache__/test_astype.cpython-310.pyc
ADDED
Binary file (3.97 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/arrays/sparse/__pycache__/test_combine_concat.cpython-310.pyc
ADDED
Binary file (2.19 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/arrays/sparse/__pycache__/test_reductions.cpython-310.pyc
ADDED
Binary file (8.29 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/arrays/sparse/__pycache__/test_unary.cpython-310.pyc
ADDED
Binary file (2.72 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/io/formats/__init__.py
ADDED
File without changes
|
venv/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (191 Bytes). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_console.cpython-310.pyc
ADDED
Binary file (2.82 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_css.cpython-310.pyc
ADDED
Binary file (6.34 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_eng_formatting.cpython-310.pyc
ADDED
Binary file (7.86 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_format.cpython-310.pyc
ADDED
Binary file (65.4 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_ipython_compat.cpython-310.pyc
ADDED
Binary file (2.97 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_printing.cpython-310.pyc
ADDED
Binary file (4.76 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_to_csv.cpython-310.pyc
ADDED
Binary file (22.4 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_to_excel.cpython-310.pyc
ADDED
Binary file (10.7 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_to_html.cpython-310.pyc
ADDED
Binary file (35.5 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_to_latex.cpython-310.pyc
ADDED
Binary file (43.9 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_to_markdown.cpython-310.pyc
ADDED
Binary file (3.12 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/io/formats/__pycache__/test_to_string.cpython-310.pyc
ADDED
Binary file (36.5 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/__init__.py
ADDED
File without changes
|
venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (197 Bytes). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_bar.cpython-310.pyc
ADDED
Binary file (9.1 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_exceptions.cpython-310.pyc
ADDED
Binary file (1.68 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_format.cpython-310.pyc
ADDED
Binary file (18.6 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_highlight.cpython-310.pyc
ADDED
Binary file (5.5 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_html.cpython-310.pyc
ADDED
Binary file (29.8 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_matplotlib.cpython-310.pyc
ADDED
Binary file (9.07 kB). View file
|
|
venv/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
|
|
venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_style.cpython-310.pyc
ADDED
Binary file (50.1 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_to_latex.cpython-310.pyc
ADDED
Binary file (28.5 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_to_string.cpython-310.pyc
ADDED
Binary file (2.13 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/__pycache__/test_tooltip.cpython-310.pyc
ADDED
Binary file (2.67 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/test_bar.py
ADDED
@@ -0,0 +1,358 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
+
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
|
venv/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)
|
venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/test_format.py
ADDED
@@ -0,0 +1,562 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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,
|
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", "<>&"%$#_{}~^\\~ ^ \\ "),
|
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&<>&">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&<>&">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"] == "&<"
|
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()
|
venv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ice,
|
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
|
venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/test_html.py
ADDED
@@ -0,0 +1,1009 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 > </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" > </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" > </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" > </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" > </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" > </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" > </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" > </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" > </th>
|
646 |
+
<th class="blank col1" > </th>
|
647 |
+
<th class="blank col2" > </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" > </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" > </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" > </th>
|
715 |
+
<th class="blank col4" > </th>
|
716 |
+
<th class="blank col5" > </th>
|
717 |
+
<th class="blank col6" > </th>
|
718 |
+
<th class="blank col7 col_trim" > </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" > </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" > </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
|
venv/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)
|
venv/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 |
+
)
|
venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/test_style.py
ADDED
@@ -0,0 +1,1588 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
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 " "
|
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" > </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"] == " "
|
1471 |
+
assert ctx["head"][1][1]["display_value"] == " "
|
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"] == " "
|
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)
|
venv/lib/python3.10/site-packages/pandas/tests/io/formats/style/test_to_latex.py
ADDED
@@ -0,0 +1,1090 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
venv/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
|
venv/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
|
venv/lib/python3.10/site-packages/pandas/tests/io/formats/test_css.py
ADDED
@@ -0,0 +1,289 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
from pandas.errors import CSSWarning
|
4 |
+
|
5 |
+
import pandas._testing as tm
|
6 |
+
|
7 |
+
from pandas.io.formats.css import CSSResolver
|
8 |
+
|
9 |
+
|
10 |
+
def assert_resolves(css, props, inherited=None):
|
11 |
+
resolve = CSSResolver()
|
12 |
+
actual = resolve(css, inherited=inherited)
|
13 |
+
assert props == actual
|
14 |
+
|
15 |
+
|
16 |
+
def assert_same_resolution(css1, css2, inherited=None):
|
17 |
+
resolve = CSSResolver()
|
18 |
+
resolved1 = resolve(css1, inherited=inherited)
|
19 |
+
resolved2 = resolve(css2, inherited=inherited)
|
20 |
+
assert resolved1 == resolved2
|
21 |
+
|
22 |
+
|
23 |
+
@pytest.mark.parametrize(
|
24 |
+
"name,norm,abnorm",
|
25 |
+
[
|
26 |
+
(
|
27 |
+
"whitespace",
|
28 |
+
"hello: world; foo: bar",
|
29 |
+
" \t hello \t :\n world \n ; \n foo: \tbar\n\n",
|
30 |
+
),
|
31 |
+
("case", "hello: world; foo: bar", "Hello: WORLD; foO: bar"),
|
32 |
+
("empty-decl", "hello: world; foo: bar", "; hello: world;; foo: bar;\n; ;"),
|
33 |
+
("empty-list", "", ";"),
|
34 |
+
],
|
35 |
+
)
|
36 |
+
def test_css_parse_normalisation(name, norm, abnorm):
|
37 |
+
assert_same_resolution(norm, abnorm)
|
38 |
+
|
39 |
+
|
40 |
+
@pytest.mark.parametrize(
|
41 |
+
"invalid_css,remainder",
|
42 |
+
[
|
43 |
+
# No colon
|
44 |
+
("hello-world", ""),
|
45 |
+
("border-style: solid; hello-world", "border-style: solid"),
|
46 |
+
(
|
47 |
+
"border-style: solid; hello-world; font-weight: bold",
|
48 |
+
"border-style: solid; font-weight: bold",
|
49 |
+
),
|
50 |
+
# Unclosed string fail
|
51 |
+
# Invalid size
|
52 |
+
("font-size: blah", "font-size: 1em"),
|
53 |
+
("font-size: 1a2b", "font-size: 1em"),
|
54 |
+
("font-size: 1e5pt", "font-size: 1em"),
|
55 |
+
("font-size: 1+6pt", "font-size: 1em"),
|
56 |
+
("font-size: 1unknownunit", "font-size: 1em"),
|
57 |
+
("font-size: 10", "font-size: 1em"),
|
58 |
+
("font-size: 10 pt", "font-size: 1em"),
|
59 |
+
# Too many args
|
60 |
+
("border-top: 1pt solid red green", "border-top: 1pt solid green"),
|
61 |
+
],
|
62 |
+
)
|
63 |
+
def test_css_parse_invalid(invalid_css, remainder):
|
64 |
+
with tm.assert_produces_warning(CSSWarning):
|
65 |
+
assert_same_resolution(invalid_css, remainder)
|
66 |
+
|
67 |
+
|
68 |
+
@pytest.mark.parametrize(
|
69 |
+
"shorthand,expansions",
|
70 |
+
[
|
71 |
+
("margin", ["margin-top", "margin-right", "margin-bottom", "margin-left"]),
|
72 |
+
("padding", ["padding-top", "padding-right", "padding-bottom", "padding-left"]),
|
73 |
+
(
|
74 |
+
"border-width",
|
75 |
+
[
|
76 |
+
"border-top-width",
|
77 |
+
"border-right-width",
|
78 |
+
"border-bottom-width",
|
79 |
+
"border-left-width",
|
80 |
+
],
|
81 |
+
),
|
82 |
+
(
|
83 |
+
"border-color",
|
84 |
+
[
|
85 |
+
"border-top-color",
|
86 |
+
"border-right-color",
|
87 |
+
"border-bottom-color",
|
88 |
+
"border-left-color",
|
89 |
+
],
|
90 |
+
),
|
91 |
+
(
|
92 |
+
"border-style",
|
93 |
+
[
|
94 |
+
"border-top-style",
|
95 |
+
"border-right-style",
|
96 |
+
"border-bottom-style",
|
97 |
+
"border-left-style",
|
98 |
+
],
|
99 |
+
),
|
100 |
+
],
|
101 |
+
)
|
102 |
+
def test_css_side_shorthands(shorthand, expansions):
|
103 |
+
top, right, bottom, left = expansions
|
104 |
+
|
105 |
+
assert_resolves(
|
106 |
+
f"{shorthand}: 1pt", {top: "1pt", right: "1pt", bottom: "1pt", left: "1pt"}
|
107 |
+
)
|
108 |
+
|
109 |
+
assert_resolves(
|
110 |
+
f"{shorthand}: 1pt 4pt", {top: "1pt", right: "4pt", bottom: "1pt", left: "4pt"}
|
111 |
+
)
|
112 |
+
|
113 |
+
assert_resolves(
|
114 |
+
f"{shorthand}: 1pt 4pt 2pt",
|
115 |
+
{top: "1pt", right: "4pt", bottom: "2pt", left: "4pt"},
|
116 |
+
)
|
117 |
+
|
118 |
+
assert_resolves(
|
119 |
+
f"{shorthand}: 1pt 4pt 2pt 0pt",
|
120 |
+
{top: "1pt", right: "4pt", bottom: "2pt", left: "0pt"},
|
121 |
+
)
|
122 |
+
|
123 |
+
with tm.assert_produces_warning(CSSWarning):
|
124 |
+
assert_resolves(f"{shorthand}: 1pt 1pt 1pt 1pt 1pt", {})
|
125 |
+
|
126 |
+
|
127 |
+
@pytest.mark.parametrize(
|
128 |
+
"shorthand,sides",
|
129 |
+
[
|
130 |
+
("border-top", ["top"]),
|
131 |
+
("border-right", ["right"]),
|
132 |
+
("border-bottom", ["bottom"]),
|
133 |
+
("border-left", ["left"]),
|
134 |
+
("border", ["top", "right", "bottom", "left"]),
|
135 |
+
],
|
136 |
+
)
|
137 |
+
def test_css_border_shorthand_sides(shorthand, sides):
|
138 |
+
def create_border_dict(sides, color=None, style=None, width=None):
|
139 |
+
resolved = {}
|
140 |
+
for side in sides:
|
141 |
+
if color:
|
142 |
+
resolved[f"border-{side}-color"] = color
|
143 |
+
if style:
|
144 |
+
resolved[f"border-{side}-style"] = style
|
145 |
+
if width:
|
146 |
+
resolved[f"border-{side}-width"] = width
|
147 |
+
return resolved
|
148 |
+
|
149 |
+
assert_resolves(
|
150 |
+
f"{shorthand}: 1pt red solid", create_border_dict(sides, "red", "solid", "1pt")
|
151 |
+
)
|
152 |
+
|
153 |
+
|
154 |
+
@pytest.mark.parametrize(
|
155 |
+
"prop, expected",
|
156 |
+
[
|
157 |
+
("1pt red solid", ("red", "solid", "1pt")),
|
158 |
+
("red 1pt solid", ("red", "solid", "1pt")),
|
159 |
+
("red solid 1pt", ("red", "solid", "1pt")),
|
160 |
+
("solid 1pt red", ("red", "solid", "1pt")),
|
161 |
+
("red solid", ("red", "solid", "1.500000pt")),
|
162 |
+
# Note: color=black is not CSS conforming
|
163 |
+
# (See https://drafts.csswg.org/css-backgrounds/#border-shorthands)
|
164 |
+
("1pt solid", ("black", "solid", "1pt")),
|
165 |
+
("1pt red", ("red", "none", "1pt")),
|
166 |
+
("red", ("red", "none", "1.500000pt")),
|
167 |
+
("1pt", ("black", "none", "1pt")),
|
168 |
+
("solid", ("black", "solid", "1.500000pt")),
|
169 |
+
# Sizes
|
170 |
+
("1em", ("black", "none", "12pt")),
|
171 |
+
],
|
172 |
+
)
|
173 |
+
def test_css_border_shorthands(prop, expected):
|
174 |
+
color, style, width = expected
|
175 |
+
|
176 |
+
assert_resolves(
|
177 |
+
f"border-left: {prop}",
|
178 |
+
{
|
179 |
+
"border-left-color": color,
|
180 |
+
"border-left-style": style,
|
181 |
+
"border-left-width": width,
|
182 |
+
},
|
183 |
+
)
|
184 |
+
|
185 |
+
|
186 |
+
@pytest.mark.parametrize(
|
187 |
+
"style,inherited,equiv",
|
188 |
+
[
|
189 |
+
("margin: 1px; margin: 2px", "", "margin: 2px"),
|
190 |
+
("margin: 1px", "margin: 2px", "margin: 1px"),
|
191 |
+
("margin: 1px; margin: inherit", "margin: 2px", "margin: 2px"),
|
192 |
+
(
|
193 |
+
"margin: 1px; margin-top: 2px",
|
194 |
+
"",
|
195 |
+
"margin-left: 1px; margin-right: 1px; "
|
196 |
+
"margin-bottom: 1px; margin-top: 2px",
|
197 |
+
),
|
198 |
+
("margin-top: 2px", "margin: 1px", "margin: 1px; margin-top: 2px"),
|
199 |
+
("margin: 1px", "margin-top: 2px", "margin: 1px"),
|
200 |
+
(
|
201 |
+
"margin: 1px; margin-top: inherit",
|
202 |
+
"margin: 2px",
|
203 |
+
"margin: 1px; margin-top: 2px",
|
204 |
+
),
|
205 |
+
],
|
206 |
+
)
|
207 |
+
def test_css_precedence(style, inherited, equiv):
|
208 |
+
resolve = CSSResolver()
|
209 |
+
inherited_props = resolve(inherited)
|
210 |
+
style_props = resolve(style, inherited=inherited_props)
|
211 |
+
equiv_props = resolve(equiv)
|
212 |
+
assert style_props == equiv_props
|
213 |
+
|
214 |
+
|
215 |
+
@pytest.mark.parametrize(
|
216 |
+
"style,equiv",
|
217 |
+
[
|
218 |
+
(
|
219 |
+
"margin: 1px; margin-top: inherit",
|
220 |
+
"margin-bottom: 1px; margin-right: 1px; margin-left: 1px",
|
221 |
+
),
|
222 |
+
("margin-top: inherit", ""),
|
223 |
+
("margin-top: initial", ""),
|
224 |
+
],
|
225 |
+
)
|
226 |
+
def test_css_none_absent(style, equiv):
|
227 |
+
assert_same_resolution(style, equiv)
|
228 |
+
|
229 |
+
|
230 |
+
@pytest.mark.parametrize(
|
231 |
+
"size,resolved",
|
232 |
+
[
|
233 |
+
("xx-small", "6pt"),
|
234 |
+
("x-small", f"{7.5:f}pt"),
|
235 |
+
("small", f"{9.6:f}pt"),
|
236 |
+
("medium", "12pt"),
|
237 |
+
("large", f"{13.5:f}pt"),
|
238 |
+
("x-large", "18pt"),
|
239 |
+
("xx-large", "24pt"),
|
240 |
+
("8px", "6pt"),
|
241 |
+
("1.25pc", "15pt"),
|
242 |
+
(".25in", "18pt"),
|
243 |
+
("02.54cm", "72pt"),
|
244 |
+
("25.4mm", "72pt"),
|
245 |
+
("101.6q", "72pt"),
|
246 |
+
("101.6q", "72pt"),
|
247 |
+
],
|
248 |
+
)
|
249 |
+
@pytest.mark.parametrize("relative_to", [None, "16pt"]) # invariant to inherited size
|
250 |
+
def test_css_absolute_font_size(size, relative_to, resolved):
|
251 |
+
if relative_to is None:
|
252 |
+
inherited = None
|
253 |
+
else:
|
254 |
+
inherited = {"font-size": relative_to}
|
255 |
+
assert_resolves(f"font-size: {size}", {"font-size": resolved}, inherited=inherited)
|
256 |
+
|
257 |
+
|
258 |
+
@pytest.mark.parametrize(
|
259 |
+
"size,relative_to,resolved",
|
260 |
+
[
|
261 |
+
("1em", None, "12pt"),
|
262 |
+
("1.0em", None, "12pt"),
|
263 |
+
("1.25em", None, "15pt"),
|
264 |
+
("1em", "16pt", "16pt"),
|
265 |
+
("1.0em", "16pt", "16pt"),
|
266 |
+
("1.25em", "16pt", "20pt"),
|
267 |
+
("1rem", "16pt", "12pt"),
|
268 |
+
("1.0rem", "16pt", "12pt"),
|
269 |
+
("1.25rem", "16pt", "15pt"),
|
270 |
+
("100%", None, "12pt"),
|
271 |
+
("125%", None, "15pt"),
|
272 |
+
("100%", "16pt", "16pt"),
|
273 |
+
("125%", "16pt", "20pt"),
|
274 |
+
("2ex", None, "12pt"),
|
275 |
+
("2.0ex", None, "12pt"),
|
276 |
+
("2.50ex", None, "15pt"),
|
277 |
+
("inherit", "16pt", "16pt"),
|
278 |
+
("smaller", None, "10pt"),
|
279 |
+
("smaller", "18pt", "15pt"),
|
280 |
+
("larger", None, f"{14.4:f}pt"),
|
281 |
+
("larger", "15pt", "18pt"),
|
282 |
+
],
|
283 |
+
)
|
284 |
+
def test_css_relative_font_size(size, relative_to, resolved):
|
285 |
+
if relative_to is None:
|
286 |
+
inherited = None
|
287 |
+
else:
|
288 |
+
inherited = {"font-size": relative_to}
|
289 |
+
assert_resolves(f"font-size: {size}", {"font-size": resolved}, inherited=inherited)
|