Skip to content
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

Make DataFrame.to_string output full content by default #28052

Merged
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
af444f0
Added a parameter to pass all the way down to specify max_colwidth. N…
Aug 21, 2019
00a43cc
I have threaded the max_colwidth parameter all over the place, but I'm
Aug 21, 2019
1ebf091
Ok, I removed all the deep changes and parameter-passing. Instead, we…
Aug 21, 2019
21bbf64
For some reason, the truncation switches justification if the max_col…
Aug 21, 2019
cfde48e
Added a test to show that this option exists for to_string
Aug 21, 2019
1abc2fa
Shortened one line (split across two). It's hard to actually shorten …
Aug 21, 2019
a1d3832
Shortened all the lines even in the test to comply with PEP8
Aug 21, 2019
3cf9a6a
Adding a newline per suggestion from isort
Aug 22, 2019
762d677
Solved the justify problem, and also added some None value for the ma…
Aug 22, 2019
d64fcb8
Swap out format to be None, ignore justification issues.
Aug 22, 2019
6e792f8
Reformat blac.
Aug 22, 2019
6a5cd97
Merge branch 'master' into issue9784-to-string-truncate-long-strings
Aug 22, 2019
889284f
Merge branch 'master' into issue9784-to-string-truncate-long-strings
Aug 27, 2019
3116ea1
Use the is_nonnegative_int validator for the max_colwidth param. I di…
Aug 27, 2019
840c1a6
Added entry to whatsnew.
Aug 27, 2019
2c68bbc
Fixed formatting with black.
Aug 27, 2019
4e7fe82
Split whatsnew entry, add versionadded, reorder params
Aug 28, 2019
90f0ee0
Remove double line break
Aug 28, 2019
c2b8421
Oops, didn't mean to update this script
Aug 28, 2019
5a8a525
Merge branch 'master' into issue9784-to-string-truncate-long-strings
Aug 28, 2019
da031f2
Correct word in whatsnew.
Aug 30, 2019
20d10b5
Merge branch 'master' into issue9784-to-string-truncate-long-strings
Aug 30, 2019
0f8119e
Update doc/source/whatsnew/v1.0.0.rst
Aug 31, 2019
732c2f4
Resolve conflict in whatsnew
Sep 5, 2019
affef02
Merge suggested edits
Sep 5, 2019
3efa1da
Merge branch 'master' into issue9784-to-string-truncate-long-strings
Sep 6, 2019
6142150
Merge branch 'master' into issue9784-to-string-truncate-long-strings
Sep 14, 2019
b23da91
Resolve conflict correctly.
Sep 14, 2019
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
2 changes: 1 addition & 1 deletion doc/source/user_guide/options.rst
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,7 @@ display.max_colwidth 50 The maximum width in charac
a column in the repr of a pandas
data structure. When the column overflows,
a "..." placeholder is embedded in
the output.
the output. 'None' value means unlimited.
display.max_info_columns 100 max_info_columns is used in DataFrame.info
method to decide if per column information
will be printed.
Expand Down
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ I/O

- :meth:`read_csv` now accepts binary mode file buffers when using the Python csv engine (:issue:`23779`)
- Bug in :meth:`DataFrame.to_json` where using a Tuple as a column or index value and using ``orient="columns"`` or ``orient="index"`` would produce invalid JSON (:issue:`20500`)
-
- Bug in :func:`DataFrame.to_string()` where values were truncated using display options instead of outputting the full content, added new param ``max_colwidth`` instead (:issue:`9784`)
TomAugspurger marked this conversation as resolved.
Show resolved Hide resolved

Plotting
^^^^^^^^
Expand Down
8 changes: 5 additions & 3 deletions pandas/core/config_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,10 +150,10 @@ def use_numexpr_cb(key):
"""

max_colwidth_doc = """
: int
: int or None
The maximum width in characters of a column in the repr of
a pandas data structure. When the column overflows, a "..."
placeholder is embedded in the output.
placeholder is embedded in the output. A 'None' value means unlimited.
"""

colheader_justify_doc = """
Expand Down Expand Up @@ -342,7 +342,9 @@ def is_terminal():
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)
TomAugspurger marked this conversation as resolved.
Show resolved Hide resolved
cf.register_option(
"max_colwidth", 50, max_colwidth_doc, validator=is_nonnegative_int
)
if is_terminal():
max_cols = 0 # automatically determine optimal number of columns
else:
Expand Down
48 changes: 28 additions & 20 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -638,6 +638,7 @@ def __repr__(self):
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")
if get_option("display.expand_frame_repr"):
width, _ = console.get_console_size()
Expand All @@ -649,6 +650,7 @@ def __repr__(self):
min_rows=min_rows,
max_cols=max_cols,
line_width=width,
max_colwidth=max_colwidth,
show_dimensions=show_dimensions,
)

Expand Down Expand Up @@ -711,11 +713,14 @@ def to_string(
max_cols=None,
show_dimensions=False,
decimal=".",
max_colwidth=None,
line_width=None,
):
"""
Render a DataFrame to a console-friendly tabular output.
%(shared_params)s
max_colwidth : int, optional
Max width to truncate each column in characters. By default, no limit.
TomAugspurger marked this conversation as resolved.
Show resolved Hide resolved
line_width : int, optional
Width to wrap a line in characters.
%(returns)s
Expand All @@ -734,26 +739,29 @@ def to_string(
2 3 6
"""

formatter = fmt.DataFrameFormatter(
self,
columns=columns,
col_space=col_space,
na_rep=na_rep,
formatters=formatters,
float_format=float_format,
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,
decimal=decimal,
line_width=line_width,
)
return formatter.to_string(buf=buf)
from pandas import option_context

with option_context("display.max_colwidth", max_colwidth):
formatter = fmt.DataFrameFormatter(
self,
columns=columns,
col_space=col_space,
na_rep=na_rep,
formatters=formatters,
float_format=float_format,
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,
decimal=decimal,
line_width=line_width,
)
return formatter.to_string(buf=buf)

# ----------------------------------------------------------------------

Expand Down
2 changes: 1 addition & 1 deletion pandas/io/clipboards.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ def to_clipboard(obj, excel=True, sep=None, **kwargs): # pragma: no cover

if isinstance(obj, ABCDataFrame):
# str(df) has various unhelpful defaults, like truncation
with option_context("display.max_colwidth", 999999):
with option_context("display.max_colwidth", None):
objstr = obj.to_string(**kwargs)
else:
objstr = str(obj)
Expand Down
2 changes: 1 addition & 1 deletion pandas/io/formats/html.py
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,7 @@ def _write_header(self, indent: int) -> None:
self.write("</thead>", indent)

def _get_formatted_values(self) -> Dict[int, List[str]]:
with option_context("display.max_colwidth", 999999):
with option_context("display.max_colwidth", None):
fmt_values = {i: self.fmt._format_col(i) for i in range(self.ncols)}
return fmt_values

Expand Down
1 change: 1 addition & 0 deletions pandas/tests/config/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,7 @@ def test_validation(self):
self.cf.set_option("a", 2) # int is_int
self.cf.set_option("b.c", "wurld") # str is_str
self.cf.set_option("d", 2)
self.cf.set_option("d", None) # non-negative int can be None

# None not is_int
with pytest.raises(ValueError, match=msg):
Expand Down
39 changes: 39 additions & 0 deletions pandas/tests/io/formats/test_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -527,6 +527,45 @@ def test_str_max_colwidth(self):
"1 foo bar stuff 1"
)

def test_to_string_truncate(self):
# GH 9784 - dont truncate when calling DataFrame.to_string
df = pd.DataFrame(
[
{
"a": "foo",
"b": "bar",
"c": "let's make this a very VERY long line that is longer "
"than the default 50 character limit",
"d": 1,
},
{"a": "foo", "b": "bar", "c": "stuff", "d": 1},
]
)
df.set_index(["a", "b", "c"])
assert df.to_string() == (
" a b "
" c d\n"
"0 foo bar let's make this a very VERY long line t"
"hat is longer than the default 50 character limit 1\n"
"1 foo bar "
" stuff 1"
)
with option_context("max_colwidth", 20):
# the display option has no effect on the to_string method
assert df.to_string() == (
" a b "
" c d\n"
"0 foo bar let's make this a very VERY long line t"
"hat is longer than the default 50 character limit 1\n"
"1 foo bar "
" stuff 1"
)
assert df.to_string(max_colwidth=20) == (
" a b c d\n"
"0 foo bar let's make this ... 1\n"
"1 foo bar stuff 1"
)

def test_auto_detect(self):
term_width, term_height = get_terminal_size()
fac = 1.05 # Arbitrary large factor to exceed term width
Expand Down