Skip to content

Shorter truncated Series/DataFrame repr: introduce min_rows #27095

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Jul 3, 2019
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions pandas/core/config_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,13 @@ def use_numexpr_cb(key):
correct auto-detection.
"""

pc_min_rows_doc = """
: int
The numbers of rows to show in a truncated view (when `max_rows` is
exceeded). Ignored when `max_rows` is set to None or 0. When set to
None, follows the value of `max_rows`.
"""

pc_max_cols_doc = """
: int
If max_cols is exceeded, switch to truncate view. Depending on
Expand Down Expand Up @@ -306,6 +313,8 @@ def is_terminal():
validator=is_instance_factory((int, type(None))))
cf.register_option('max_rows', 60, pc_max_rows_doc,
validator=is_instance_factory([type(None), int]))
cf.register_option('min_rows', 10, pc_min_rows_doc,
validator=is_instance_factory([type(None), int]))
cf.register_option('max_categories', 8, pc_max_categories_doc,
validator=is_int)
cf.register_option('max_colwidth', 50, max_colwidth_doc, validator=is_int)
Expand Down
11 changes: 7 additions & 4 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -588,14 +588,16 @@ def __repr__(self):
return buf.getvalue()

max_rows = get_option("display.max_rows")
min_rows = get_option("display.min_rows")
max_cols = get_option("display.max_columns")
show_dimensions = get_option("display.show_dimensions")
if get_option("display.expand_frame_repr"):
width, _ = console.get_console_size()
else:
width = None
self.to_string(buf=buf, max_rows=max_rows, max_cols=max_cols,
line_width=width, show_dimensions=show_dimensions)
self.to_string(buf=buf, max_rows=max_rows, min_rows=min_rows,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can the logic be added before this call to .to_string (isn't it as simple as just set max_rows to min_rows if len(self.frame) > max_rows?)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For the simple cases, yes. And I agree that could be a nice option. But there are some corner cases that are only handled within the DataFrameFormatter class (eg if max_rows = 0, we check the terminal size)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Although, looking at it more closely, that special case is only if max_rows is 0 or None, so that could be easily checked. So yes, this would in principle be possible (and probably even give easier code). But that means that we move some of the logic of the repr out of the Formatter class.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But that means that we move some of the logic of the repr out of the Formatter class.

i agree. but this logic is related to display options. i'd prefer to see all the display option handling removed from the Formatter classes entirely and only appear in __repr__ and _repr_html_

it appears from the comments that adding arguments to to_string is not considered undesirable. so this topic can be addressed another day.

max_cols=max_cols, line_width=width,
show_dimensions=show_dimensions)

return buf.getvalue()

Expand Down Expand Up @@ -633,8 +635,8 @@ def _repr_html_(self):
def to_string(self, buf=None, columns=None, col_space=None, header=True,
index=True, na_rep='NaN', formatters=None, float_format=None,
sparsify=None, index_names=True, justify=None,
max_rows=None, max_cols=None, show_dimensions=False,
decimal='.', line_width=None):
min_rows=None, max_rows=None, max_cols=None,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you add types on new args (and old ones if you can)

show_dimensions=False, decimal='.', line_width=None):
"""
Render a DataFrame to a console-friendly tabular output.
%(shared_params)s
Expand Down Expand Up @@ -663,6 +665,7 @@ def to_string(self, buf=None, columns=None, col_space=None, header=True,
sparsify=sparsify, justify=justify,
index_names=index_names,
header=header, index=index,
min_rows=min_rows,
max_rows=max_rows,
max_cols=max_cols,
show_dimensions=show_dimensions,
Expand Down
8 changes: 6 additions & 2 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -1486,17 +1486,20 @@ def __repr__(self):
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"))
show_dimensions = get_option("display.show_dimensions")

self.to_string(buf=buf, name=self.name, dtype=self.dtype,
max_rows=max_rows, length=show_dimensions)
min_rows=min_rows, max_rows=max_rows,
length=show_dimensions)
result = buf.getvalue()

return result

def to_string(self, buf=None, na_rep='NaN', float_format=None, header=True,
index=True, length=False, dtype=False, name=False,
max_rows=None):
min_rows=None, max_rows=None):
"""
Render a string representation of the Series.

Expand Down Expand Up @@ -1533,6 +1536,7 @@ def to_string(self, buf=None, na_rep='NaN', float_format=None, header=True,
header=header, index=index,
dtype=dtype, na_rep=na_rep,
float_format=float_format,
min_rows=min_rows,
max_rows=max_rows)
result = formatter.to_string()

Expand Down
31 changes: 23 additions & 8 deletions pandas/io/formats/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,14 +159,15 @@ class SeriesFormatter:

def __init__(self, series, buf=None, length=True, header=True, index=True,
na_rep='NaN', name=False, float_format=None, dtype=True,
max_rows=None):
min_rows=None, max_rows=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.min_rows = min_rows
self.max_rows = max_rows

if float_format is None:
Expand All @@ -179,15 +180,24 @@ def __init__(self, series, buf=None, length=True, header=True, index=True,

def _chk_truncate(self):
from pandas.core.reshape.concat import concat
min_rows = self.min_rows
max_rows = self.max_rows
# if min_rows is None, follow value of max_rows
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

None or 0

if max_rows and not min_rows:
min_rows = max_rows
# if both are set, min_rows is minimum of both
if min_rows and max_rows:
min_rows = min(min_rows, max_rows)
# truncation determined by max_rows, actual truncated number of rows
# used below by min_rows
truncate_v = max_rows and (len(self.series) > max_rows)
series = self.series
if truncate_v:
if max_rows == 1:
row_num = max_rows
series = series.iloc[:max_rows]
if min_rows == 1:
row_num = min_rows
series = series.iloc[:min_rows]
else:
row_num = max_rows // 2
row_num = min_rows // 2
series = concat((series.iloc[:row_num],
series.iloc[-row_num:]))
self.tr_row_num = row_num
Expand Down Expand Up @@ -390,9 +400,9 @@ class DataFrameFormatter(TableFormatter):
def __init__(self, frame, buf=None, columns=None, col_space=None,
header=True, index=True, na_rep='NaN', formatters=None,
justify=None, float_format=None, sparsify=None,
index_names=True, line_width=None, max_rows=None,
max_cols=None, show_dimensions=False, decimal='.',
table_id=None, render_links=False, **kwds):
index_names=True, line_width=None, min_rows=None,
max_rows=None, max_cols=None, show_dimensions=False,
decimal='.', table_id=None, render_links=False, **kwds):
self.frame = frame
if buf is not None:
self.buf = _expand_user(_stringify_path(buf))
Expand All @@ -413,6 +423,7 @@ def __init__(self, frame, buf=None, columns=None, col_space=None,
self.header = header
self.index = index
self.line_width = line_width
self.min_rows = min_rows
self.max_rows = max_rows
self.max_cols = max_cols
self.max_rows_displayed = min(max_rows or len(self.frame),
Expand Down Expand Up @@ -471,6 +482,10 @@ def _chk_truncate(self):
max_rows = h

if not hasattr(self, 'max_rows_adj'):
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)
self.max_rows_adj = max_rows
if not hasattr(self, 'max_cols_adj'):
self.max_cols_adj = max_cols
Expand Down
56 changes: 56 additions & 0 deletions pandas/tests/io/formats/test_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,34 @@ def mkframe(n):
printing.pprint_thing(df._repr_fits_horizontal_())
assert has_expanded_repr(df)

def test_repr_min_rows(self):
df = pd.DataFrame({'a': range(20)})

# default setting no truncation even if above min_rows
assert '..' not in repr(df)

df = pd.DataFrame({'a': range(61)})

# default of max_rows 60 triggers truncation if above
assert '..' in repr(df)

with option_context('display.max_rows', 10, 'display.min_rows', 4):
# truncated after first two rows
assert '..' in repr(df)
assert '2 ' not in repr(df)

with option_context('display.max_rows', 12, 'display.min_rows', None):
# when set to None, follow value of max_rows
assert '5 5' in repr(df)

with option_context('display.max_rows', 10, 'display.min_rows', 12):
# when set value higher as max_rows, use the minimum
assert '5 5' not in repr(df)

with option_context('display.max_rows', None, 'display.min_rows', 12):
# max_rows of None -> never truncate
assert '..' not in repr(df)

def test_str_max_colwidth(self):
# GH 7856
df = pd.DataFrame([{'a': 'foo',
Expand Down Expand Up @@ -2284,6 +2312,34 @@ def test_show_dimensions(self):
"display.show_dimensions", False):
assert 'Length' not in repr(s)

def test_repr_min_rows(self):
s = pd.Series(range(20))

# default setting no truncation even if above min_rows
assert '..' not in repr(s)

s = pd.Series(range(61))

# default of max_rows 60 triggers truncation if above
assert '..' in repr(s)

with option_context('display.max_rows', 10, 'display.min_rows', 4):
# truncated after first two rows
assert '..' in repr(s)
assert '2 ' not in repr(s)

with option_context('display.max_rows', 12, 'display.min_rows', None):
# when set to None, follow value of max_rows
assert '5 5' in repr(s)

with option_context('display.max_rows', 10, 'display.min_rows', 12):
# when set value higher as max_rows, use the minimum
assert '5 5' not in repr(s)

with option_context('display.max_rows', None, 'display.min_rows', 12):
# max_rows of None -> never truncate
assert '..' not in repr(s)

def test_to_string_name(self):
s = Series(range(100), dtype='int64')
s.name = 'myser'
Expand Down