-
-
Notifications
You must be signed in to change notification settings - Fork 18.1k
/
format.py
2200 lines (1844 loc) · 68.1 KB
/
format.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Internal module for formatting output data in csv, html, xml,
and latex files. This module also applies to display formatting.
"""
from __future__ import annotations
from contextlib import contextmanager
from csv import (
QUOTE_NONE,
QUOTE_NONNUMERIC,
)
from decimal import Decimal
from functools import partial
from io import StringIO
import math
import re
from shutil import get_terminal_size
from typing import (
IO,
TYPE_CHECKING,
Any,
Callable,
Final,
Generator,
Hashable,
Iterable,
List,
Mapping,
Sequence,
cast,
)
from unicodedata import east_asian_width
import numpy as np
from pandas._config.config import (
get_option,
set_option,
)
from pandas._libs import lib
from pandas._libs.missing import NA
from pandas._libs.tslibs import (
NaT,
Timedelta,
Timestamp,
get_unit_from_dtype,
iNaT,
periods_per_day,
)
from pandas._libs.tslibs.nattype import NaTType
from pandas.core.dtypes.common import (
is_complex_dtype,
is_float,
is_integer,
is_list_like,
is_numeric_dtype,
is_scalar,
)
from pandas.core.dtypes.dtypes import (
CategoricalDtype,
DatetimeTZDtype,
ExtensionDtype,
)
from pandas.core.dtypes.missing import (
isna,
notna,
)
from pandas.core.arrays import (
Categorical,
DatetimeArray,
TimedeltaArray,
)
from pandas.core.arrays.string_ import StringDtype
from pandas.core.base import PandasObject
import pandas.core.common as com
from pandas.core.construction import extract_array
from pandas.core.indexes.api import (
Index,
MultiIndex,
PeriodIndex,
ensure_index,
)
from pandas.core.indexes.datetimes import DatetimeIndex
from pandas.core.indexes.timedeltas import TimedeltaIndex
from pandas.core.reshape.concat import concat
from pandas.io.common import (
check_parent_directory,
stringify_path,
)
from pandas.io.formats import printing
if TYPE_CHECKING:
from pandas._typing import (
ArrayLike,
Axes,
ColspaceArgType,
ColspaceType,
CompressionOptions,
FilePath,
FloatFormatType,
FormattersType,
IndexLabel,
StorageOptions,
WriteBuffer,
)
from pandas import (
DataFrame,
Series,
)
common_docstring: Final = """
Parameters
----------
buf : str, Path or StringIO-like, optional, default None
Buffer to write to. If None, the output is returned as a string.
columns : array-like, optional, default None
The subset of columns to write. Writes all columns by default.
col_space : %(col_space_type)s, optional
%(col_space)s.
header : %(header_type)s, optional
%(header)s.
index : bool, optional, default True
Whether to print index (row) labels.
na_rep : str, optional, default 'NaN'
String representation of ``NaN`` to use.
formatters : list, tuple or dict of one-param. functions, optional
Formatter functions to apply to columns' elements by position or
name.
The result of each function must be a unicode string.
List/tuple must be of length equal to the number of columns.
float_format : one-parameter function, optional, default None
Formatter function to apply to columns' elements if they are
floats. This function must return a unicode string and will be
applied only to the non-``NaN`` elements, with ``NaN`` being
handled by ``na_rep``.
.. versionchanged:: 1.2.0
sparsify : bool, optional, default True
Set to False for a DataFrame with a hierarchical index to print
every multiindex key at each row.
index_names : bool, optional, default True
Prints the names of the indexes.
justify : str, default None
How to justify the column labels. If None uses the option from
the print configuration (controlled by set_option), 'right' out
of the box. Valid values are
* left
* right
* center
* justify
* justify-all
* start
* end
* inherit
* match-parent
* initial
* unset.
max_rows : int, optional
Maximum number of rows to display in the console.
max_cols : int, optional
Maximum number of columns to display in the console.
show_dimensions : bool, default False
Display DataFrame dimensions (number of rows by number of columns).
decimal : str, default '.'
Character recognized as decimal separator, e.g. ',' in Europe.
"""
_VALID_JUSTIFY_PARAMETERS = (
"left",
"right",
"center",
"justify",
"justify-all",
"start",
"end",
"inherit",
"match-parent",
"initial",
"unset",
)
return_docstring: Final = """
Returns
-------
str or None
If buf is None, returns the result as a string. Otherwise returns
None.
"""
class CategoricalFormatter:
def __init__(
self,
categorical: Categorical,
buf: IO[str] | None = None,
length: bool = True,
na_rep: str = "NaN",
footer: bool = True,
) -> None:
self.categorical = categorical
self.buf = buf if buf is not None else StringIO("")
self.na_rep = na_rep
self.length = length
self.footer = footer
self.quoting = QUOTE_NONNUMERIC
def _get_footer(self) -> str:
footer = ""
if self.length:
if footer:
footer += ", "
footer += f"Length: {len(self.categorical)}"
level_info = self.categorical._repr_categories_info()
# Levels are added in a newline
if footer:
footer += "\n"
footer += level_info
return str(footer)
def _get_formatted_values(self) -> list[str]:
return format_array(
self.categorical._internal_get_values(),
None,
float_format=None,
na_rep=self.na_rep,
quoting=self.quoting,
)
def to_string(self) -> str:
categorical = self.categorical
if len(categorical) == 0:
if self.footer:
return self._get_footer()
else:
return ""
fmt_values = self._get_formatted_values()
fmt_values = [i.strip() for i in fmt_values]
values = ", ".join(fmt_values)
result = ["[" + values + "]"]
if self.footer:
footer = self._get_footer()
if footer:
result.append(footer)
return str("\n".join(result))
class SeriesFormatter:
def __init__(
self,
series: Series,
buf: IO[str] | None = None,
length: bool | str = True,
header: bool = True,
index: bool = True,
na_rep: str = "NaN",
name: bool = False,
float_format: str | None = None,
dtype: bool = True,
max_rows: int | None = None,
min_rows: int | None = None,
) -> None:
self.series = series
self.buf = buf if buf is not None else StringIO()
self.name = name
self.na_rep = na_rep
self.header = header
self.length = length
self.index = index
self.max_rows = max_rows
self.min_rows = min_rows
if float_format is None:
float_format = get_option("display.float_format")
self.float_format = float_format
self.dtype = dtype
self.adj = get_adjustment()
self._chk_truncate()
def _chk_truncate(self) -> None:
self.tr_row_num: int | None
min_rows = self.min_rows
max_rows = self.max_rows
# truncation determined by max_rows, actual truncated number of rows
# used below by min_rows
is_truncated_vertically = max_rows and (len(self.series) > max_rows)
series = self.series
if is_truncated_vertically:
max_rows = cast(int, max_rows)
if min_rows:
# if min_rows is set (not None or 0), set max_rows to minimum
# of both
max_rows = min(min_rows, max_rows)
if max_rows == 1:
row_num = max_rows
series = series.iloc[:max_rows]
else:
row_num = max_rows // 2
series = concat((series.iloc[:row_num], series.iloc[-row_num:]))
self.tr_row_num = row_num
else:
self.tr_row_num = None
self.tr_series = series
self.is_truncated_vertically = is_truncated_vertically
def _get_footer(self) -> str:
name = self.series.name
footer = ""
if getattr(self.series.index, "freq", None) is not None:
assert isinstance(
self.series.index, (DatetimeIndex, PeriodIndex, TimedeltaIndex)
)
footer += f"Freq: {self.series.index.freqstr}"
if self.name is not False and name is not None:
if footer:
footer += ", "
series_name = printing.pprint_thing(name, escape_chars=("\t", "\r", "\n"))
footer += f"Name: {series_name}"
if self.length is True or (
self.length == "truncate" and self.is_truncated_vertically
):
if footer:
footer += ", "
footer += f"Length: {len(self.series)}"
if self.dtype is not False and self.dtype is not None:
dtype_name = getattr(self.tr_series.dtype, "name", None)
if dtype_name:
if footer:
footer += ", "
footer += f"dtype: {printing.pprint_thing(dtype_name)}"
# level infos are added to the end and in a new line, like it is done
# for Categoricals
if isinstance(self.tr_series.dtype, CategoricalDtype):
level_info = self.tr_series._values._repr_categories_info()
if footer:
footer += "\n"
footer += level_info
return str(footer)
def _get_formatted_index(self) -> tuple[list[str], bool]:
index = self.tr_series.index
if isinstance(index, MultiIndex):
have_header = any(name for name in index.names)
fmt_index = index.format(names=True)
else:
have_header = index.name is not None
fmt_index = index.format(name=True)
return fmt_index, have_header
def _get_formatted_values(self) -> list[str]:
return format_array(
self.tr_series._values,
None,
float_format=self.float_format,
na_rep=self.na_rep,
leading_space=self.index,
)
def to_string(self) -> str:
series = self.tr_series
footer = self._get_footer()
if len(series) == 0:
return f"{type(self.series).__name__}([], {footer})"
fmt_index, have_header = self._get_formatted_index()
fmt_values = self._get_formatted_values()
if self.is_truncated_vertically:
n_header_rows = 0
row_num = self.tr_row_num
row_num = cast(int, row_num)
width = self.adj.len(fmt_values[row_num - 1])
if width > 3:
dot_str = "..."
else:
dot_str = ".."
# Series uses mode=center because it has single value columns
# DataFrame uses mode=left
dot_str = self.adj.justify([dot_str], width, mode="center")[0]
fmt_values.insert(row_num + n_header_rows, dot_str)
fmt_index.insert(row_num + 1, "")
if self.index:
result = self.adj.adjoin(3, *[fmt_index[1:], fmt_values])
else:
result = self.adj.adjoin(3, fmt_values)
if self.header and have_header:
result = fmt_index[0] + "\n" + result
if footer:
result += "\n" + footer
return str("".join(result))
class TextAdjustment:
def __init__(self) -> None:
self.encoding = get_option("display.encoding")
def len(self, text: str) -> int:
return len(text)
def justify(self, texts: Any, max_len: int, mode: str = "right") -> list[str]:
return printing.justify(texts, max_len, mode=mode)
def adjoin(self, space: int, *lists, **kwargs) -> str:
return printing.adjoin(
space, *lists, strlen=self.len, justfunc=self.justify, **kwargs
)
class EastAsianTextAdjustment(TextAdjustment):
def __init__(self) -> None:
super().__init__()
if get_option("display.unicode.ambiguous_as_wide"):
self.ambiguous_width = 2
else:
self.ambiguous_width = 1
# Definition of East Asian Width
# https://unicode.org/reports/tr11/
# Ambiguous width can be changed by option
self._EAW_MAP = {"Na": 1, "N": 1, "W": 2, "F": 2, "H": 1}
def len(self, text: str) -> int:
"""
Calculate display width considering unicode East Asian Width
"""
if not isinstance(text, str):
return len(text)
return sum(
self._EAW_MAP.get(east_asian_width(c), self.ambiguous_width) for c in text
)
def justify(
self, texts: Iterable[str], max_len: int, mode: str = "right"
) -> list[str]:
# re-calculate padding space per str considering East Asian Width
def _get_pad(t):
return max_len - self.len(t) + len(t)
if mode == "left":
return [x.ljust(_get_pad(x)) for x in texts]
elif mode == "center":
return [x.center(_get_pad(x)) for x in texts]
else:
return [x.rjust(_get_pad(x)) for x in texts]
def get_adjustment() -> TextAdjustment:
use_east_asian_width = get_option("display.unicode.east_asian_width")
if use_east_asian_width:
return EastAsianTextAdjustment()
else:
return TextAdjustment()
def get_dataframe_repr_params() -> dict[str, Any]:
"""Get the parameters used to repr(dataFrame) calls using DataFrame.to_string.
Supplying these parameters to DataFrame.to_string is equivalent to calling
``repr(DataFrame)``. This is useful if you want to adjust the repr output.
.. versionadded:: 1.4.0
Example
-------
>>> import pandas as pd
>>>
>>> df = pd.DataFrame([[1, 2], [3, 4]])
>>> repr_params = pd.io.formats.format.get_dataframe_repr_params()
>>> repr(df) == df.to_string(**repr_params)
True
"""
from pandas.io.formats import console
if get_option("display.expand_frame_repr"):
line_width, _ = console.get_console_size()
else:
line_width = None
return {
"max_rows": get_option("display.max_rows"),
"min_rows": get_option("display.min_rows"),
"max_cols": get_option("display.max_columns"),
"max_colwidth": get_option("display.max_colwidth"),
"show_dimensions": get_option("display.show_dimensions"),
"line_width": line_width,
}
def get_series_repr_params() -> dict[str, Any]:
"""Get the parameters used to repr(Series) calls using Series.to_string.
Supplying these parameters to Series.to_string is equivalent to calling
``repr(series)``. This is useful if you want to adjust the series repr output.
.. versionadded:: 1.4.0
Example
-------
>>> import pandas as pd
>>>
>>> ser = pd.Series([1, 2, 3, 4])
>>> repr_params = pd.io.formats.format.get_series_repr_params()
>>> repr(ser) == ser.to_string(**repr_params)
True
"""
width, height = get_terminal_size()
max_rows = (
height
if get_option("display.max_rows") == 0
else get_option("display.max_rows")
)
min_rows = (
height
if get_option("display.max_rows") == 0
else get_option("display.min_rows")
)
return {
"name": True,
"dtype": True,
"min_rows": min_rows,
"max_rows": max_rows,
"length": get_option("display.show_dimensions"),
}
class DataFrameFormatter:
"""Class for processing dataframe formatting options and data."""
__doc__ = __doc__ if __doc__ else ""
__doc__ += common_docstring + return_docstring
def __init__(
self,
frame: DataFrame,
columns: Axes | None = None,
col_space: ColspaceArgType | None = None,
header: bool | list[str] = True,
index: bool = True,
na_rep: str = "NaN",
formatters: FormattersType | None = None,
justify: str | None = None,
float_format: FloatFormatType | None = None,
sparsify: bool | None = None,
index_names: bool = True,
max_rows: int | None = None,
min_rows: int | None = None,
max_cols: int | None = None,
show_dimensions: bool | str = False,
decimal: str = ".",
bold_rows: bool = False,
escape: bool = True,
) -> None:
self.frame = frame
self.columns = self._initialize_columns(columns)
self.col_space = self._initialize_colspace(col_space)
self.header = header
self.index = index
self.na_rep = na_rep
self.formatters = self._initialize_formatters(formatters)
self.justify = self._initialize_justify(justify)
self.float_format = float_format
self.sparsify = self._initialize_sparsify(sparsify)
self.show_index_names = index_names
self.decimal = decimal
self.bold_rows = bold_rows
self.escape = escape
self.max_rows = max_rows
self.min_rows = min_rows
self.max_cols = max_cols
self.show_dimensions = show_dimensions
self.max_cols_fitted = self._calc_max_cols_fitted()
self.max_rows_fitted = self._calc_max_rows_fitted()
self.tr_frame = self.frame
self.truncate()
self.adj = get_adjustment()
def get_strcols(self) -> list[list[str]]:
"""
Render a DataFrame to a list of columns (as lists of strings).
"""
strcols = self._get_strcols_without_index()
if self.index:
str_index = self._get_formatted_index(self.tr_frame)
strcols.insert(0, str_index)
return strcols
@property
def should_show_dimensions(self) -> bool:
return self.show_dimensions is True or (
self.show_dimensions == "truncate" and self.is_truncated
)
@property
def is_truncated(self) -> bool:
return bool(self.is_truncated_horizontally or self.is_truncated_vertically)
@property
def is_truncated_horizontally(self) -> bool:
return bool(self.max_cols_fitted and (len(self.columns) > self.max_cols_fitted))
@property
def is_truncated_vertically(self) -> bool:
return bool(self.max_rows_fitted and (len(self.frame) > self.max_rows_fitted))
@property
def dimensions_info(self) -> str:
return f"\n\n[{len(self.frame)} rows x {len(self.frame.columns)} columns]"
@property
def has_index_names(self) -> bool:
return _has_names(self.frame.index)
@property
def has_column_names(self) -> bool:
return _has_names(self.frame.columns)
@property
def show_row_idx_names(self) -> bool:
return all((self.has_index_names, self.index, self.show_index_names))
@property
def show_col_idx_names(self) -> bool:
return all((self.has_column_names, self.show_index_names, self.header))
@property
def max_rows_displayed(self) -> int:
return min(self.max_rows or len(self.frame), len(self.frame))
def _initialize_sparsify(self, sparsify: bool | None) -> bool:
if sparsify is None:
return get_option("display.multi_sparse")
return sparsify
def _initialize_formatters(
self, formatters: FormattersType | None
) -> FormattersType:
if formatters is None:
return {}
elif len(self.frame.columns) == len(formatters) or isinstance(formatters, dict):
return formatters
else:
raise ValueError(
f"Formatters length({len(formatters)}) should match "
f"DataFrame number of columns({len(self.frame.columns)})"
)
def _initialize_justify(self, justify: str | None) -> str:
if justify is None:
return get_option("display.colheader_justify")
else:
return justify
def _initialize_columns(self, columns: Axes | None) -> Index:
if columns is not None:
cols = ensure_index(columns)
self.frame = self.frame[cols]
return cols
else:
return self.frame.columns
def _initialize_colspace(self, col_space: ColspaceArgType | None) -> ColspaceType:
result: ColspaceType
if col_space is None:
result = {}
elif isinstance(col_space, (int, str)):
result = {"": col_space}
result.update({column: col_space for column in self.frame.columns})
elif isinstance(col_space, Mapping):
for column in col_space.keys():
if column not in self.frame.columns and column != "":
raise ValueError(
f"Col_space is defined for an unknown column: {column}"
)
result = col_space
else:
if len(self.frame.columns) != len(col_space):
raise ValueError(
f"Col_space length({len(col_space)}) should match "
f"DataFrame number of columns({len(self.frame.columns)})"
)
result = dict(zip(self.frame.columns, col_space))
return result
def _calc_max_cols_fitted(self) -> int | None:
"""Number of columns fitting the screen."""
if not self._is_in_terminal():
return self.max_cols
width, _ = get_terminal_size()
if self._is_screen_narrow(width):
return width
else:
return self.max_cols
def _calc_max_rows_fitted(self) -> int | None:
"""Number of rows with data fitting the screen."""
max_rows: int | None
if self._is_in_terminal():
_, height = get_terminal_size()
if self.max_rows == 0:
# rows available to fill with actual data
return height - self._get_number_of_auxiliary_rows()
if self._is_screen_short(height):
max_rows = height
else:
max_rows = self.max_rows
else:
max_rows = self.max_rows
return self._adjust_max_rows(max_rows)
def _adjust_max_rows(self, max_rows: int | None) -> int | None:
"""Adjust max_rows using display logic.
See description here:
https://pandas.pydata.org/docs/dev/user_guide/options.html#frequently-used-options
GH #37359
"""
if max_rows:
if (len(self.frame) > max_rows) and self.min_rows:
# if truncated, set max_rows showed to min_rows
max_rows = min(self.min_rows, max_rows)
return max_rows
def _is_in_terminal(self) -> bool:
"""Check if the output is to be shown in terminal."""
return bool(self.max_cols == 0 or self.max_rows == 0)
def _is_screen_narrow(self, max_width) -> bool:
return bool(self.max_cols == 0 and len(self.frame.columns) > max_width)
def _is_screen_short(self, max_height) -> bool:
return bool(self.max_rows == 0 and len(self.frame) > max_height)
def _get_number_of_auxiliary_rows(self) -> int:
"""Get number of rows occupied by prompt, dots and dimension info."""
dot_row = 1
prompt_row = 1
num_rows = dot_row + prompt_row
if self.show_dimensions:
num_rows += len(self.dimensions_info.splitlines())
if self.header:
num_rows += 1
return num_rows
def truncate(self) -> None:
"""
Check whether the frame should be truncated. If so, slice the frame up.
"""
if self.is_truncated_horizontally:
self._truncate_horizontally()
if self.is_truncated_vertically:
self._truncate_vertically()
def _truncate_horizontally(self) -> None:
"""Remove columns, which are not to be displayed and adjust formatters.
Attributes affected:
- tr_frame
- formatters
- tr_col_num
"""
assert self.max_cols_fitted is not None
col_num = self.max_cols_fitted // 2
if col_num >= 1:
left = self.tr_frame.iloc[:, :col_num]
right = self.tr_frame.iloc[:, -col_num:]
self.tr_frame = concat((left, right), axis=1)
# truncate formatter
if isinstance(self.formatters, (list, tuple)):
self.formatters = [
*self.formatters[:col_num],
*self.formatters[-col_num:],
]
else:
col_num = cast(int, self.max_cols)
self.tr_frame = self.tr_frame.iloc[:, :col_num]
self.tr_col_num = col_num
def _truncate_vertically(self) -> None:
"""Remove rows, which are not to be displayed.
Attributes affected:
- tr_frame
- tr_row_num
"""
assert self.max_rows_fitted is not None
row_num = self.max_rows_fitted // 2
if row_num >= 1:
head = self.tr_frame.iloc[:row_num, :]
tail = self.tr_frame.iloc[-row_num:, :]
self.tr_frame = concat((head, tail))
else:
row_num = cast(int, self.max_rows)
self.tr_frame = self.tr_frame.iloc[:row_num, :]
self.tr_row_num = row_num
def _get_strcols_without_index(self) -> list[list[str]]:
strcols: list[list[str]] = []
if not is_list_like(self.header) and not self.header:
for i, c in enumerate(self.tr_frame):
fmt_values = self.format_col(i)
fmt_values = _make_fixed_width(
strings=fmt_values,
justify=self.justify,
minimum=int(self.col_space.get(c, 0)),
adj=self.adj,
)
strcols.append(fmt_values)
return strcols
if is_list_like(self.header):
# cast here since can't be bool if is_list_like
self.header = cast(List[str], self.header)
if len(self.header) != len(self.columns):
raise ValueError(
f"Writing {len(self.columns)} cols "
f"but got {len(self.header)} aliases"
)
str_columns = [[label] for label in self.header]
else:
str_columns = self._get_formatted_column_labels(self.tr_frame)
if self.show_row_idx_names:
for x in str_columns:
x.append("")
for i, c in enumerate(self.tr_frame):
cheader = str_columns[i]
header_colwidth = max(
int(self.col_space.get(c, 0)), *(self.adj.len(x) for x in cheader)
)
fmt_values = self.format_col(i)
fmt_values = _make_fixed_width(
fmt_values, self.justify, minimum=header_colwidth, adj=self.adj
)
max_len = max(*(self.adj.len(x) for x in fmt_values), header_colwidth)
cheader = self.adj.justify(cheader, max_len, mode=self.justify)
strcols.append(cheader + fmt_values)
return strcols
def format_col(self, i: int) -> list[str]:
frame = self.tr_frame
formatter = self._get_formatter(i)
return format_array(
frame.iloc[:, i]._values,
formatter,
float_format=self.float_format,
na_rep=self.na_rep,
space=self.col_space.get(frame.columns[i]),
decimal=self.decimal,
leading_space=self.index,
)
def _get_formatter(self, i: str | int) -> Callable | None:
if isinstance(self.formatters, (list, tuple)):
if is_integer(i):
i = cast(int, i)
return self.formatters[i]
else:
return None
else:
if is_integer(i) and i not in self.columns:
i = self.columns[i]
return self.formatters.get(i, None)
def _get_formatted_column_labels(self, frame: DataFrame) -> list[list[str]]:
from pandas.core.indexes.multi import sparsify_labels
columns = frame.columns
if isinstance(columns, MultiIndex):
fmt_columns = columns.format(sparsify=False, adjoin=False)
fmt_columns = list(zip(*fmt_columns))
dtypes = self.frame.dtypes._values
# if we have a Float level, they don't use leading space at all
restrict_formatting = any(level.is_floating for level in columns.levels)
need_leadsp = dict(zip(fmt_columns, map(is_numeric_dtype, dtypes)))
def space_format(x, y):
if (
y not in self.formatters
and need_leadsp[x]
and not restrict_formatting
):
return " " + y
return y
str_columns = list(
zip(*([space_format(x, y) for y in x] for x in fmt_columns))
)
if self.sparsify and len(str_columns):
str_columns = sparsify_labels(str_columns)
str_columns = [list(x) for x in zip(*str_columns)]
else:
fmt_columns = columns.format()
dtypes = self.frame.dtypes
need_leadsp = dict(zip(fmt_columns, map(is_numeric_dtype, dtypes)))
str_columns = [
[" " + x if not self._get_formatter(i) and need_leadsp[x] else x]
for i, x in enumerate(fmt_columns)
]
# self.str_columns = str_columns
return str_columns
def _get_formatted_index(self, frame: DataFrame) -> list[str]:
# Note: this is only used by to_string() and to_latex(), not by
# to_html(). so safe to cast col_space here.
col_space = {k: cast(int, v) for k, v in self.col_space.items()}
index = frame.index
columns = frame.columns
fmt = self._get_formatter("__index__")
if isinstance(index, MultiIndex):
fmt_index = index.format(
sparsify=self.sparsify,
adjoin=False,
names=self.show_row_idx_names,
formatter=fmt,
)
else:
fmt_index = [index.format(name=self.show_row_idx_names, formatter=fmt)]
fmt_index = [
tuple(
_make_fixed_width(
list(x), justify="left", minimum=col_space.get("", 0), adj=self.adj
)
)
for x in fmt_index
]
adjoined = self.adj.adjoin(1, *fmt_index).split("\n")
# empty space for columns
if self.show_col_idx_names:
col_header = [str(x) for x in self._get_column_name_list()]
else:
col_header = [""] * columns.nlevels
if self.header:
return col_header + adjoined
else:
return adjoined
def _get_column_name_list(self) -> list[Hashable]:
names: list[Hashable] = []
columns = self.frame.columns
if isinstance(columns, MultiIndex):
names.extend("" if name is None else name for name in columns.names)
else: