Skip to content

Commit

Permalink
Backport PR #54801 on branch 2.1.x (BUG: repr aligning left for strin…
Browse files Browse the repository at this point in the history
…g dtype columns) (#54819)

Backport PR #54801: BUG: repr aligning left for string dtype columns

Co-authored-by: Patrick Hoefler <61934744+phofl@users.noreply.github.com>
  • Loading branch information
meeseeksmachine and phofl committed Aug 28, 2023
1 parent 891ea9b commit 7961b1c
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 2 deletions.
1 change: 1 addition & 0 deletions doc/source/whatsnew/v2.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -717,6 +717,7 @@ Conversion
Strings
^^^^^^^
- Bug in :meth:`Series.str` that did not raise a ``TypeError`` when iterated (:issue:`54173`)
- Bug in ``repr`` for :class:`DataFrame`` with string-dtype columns (:issue:`54797`)

Interval
^^^^^^^^
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1419,8 +1419,8 @@ def _format_with_header(self, header: list[str_t], na_rep: str_t) -> list[str_t]

values = self._values

if is_object_dtype(values.dtype):
values = cast(np.ndarray, values)
if is_object_dtype(values.dtype) or is_string_dtype(values.dtype):
values = np.asarray(values)
values = lib.maybe_convert_objects(values, safe=True)

result = [pprint_thing(x, escape_chars=("\t", "\r", "\n")) for x in values]
Expand Down
11 changes: 11 additions & 0 deletions pandas/tests/frame/test_repr_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -455,3 +455,14 @@ def test_masked_ea_with_formatter(self):
0 0.12 1.00
1 1.12 2.00"""
assert result == expected

def test_repr_ea_columns(self, any_string_dtype):
# GH#54797
pytest.importorskip("pyarrow")
df = DataFrame({"long_column_name": [1, 2, 3], "col2": [4, 5, 6]})
df.columns = df.columns.astype(any_string_dtype)
expected = """ long_column_name col2
0 1 4
1 2 5
2 3 6"""
assert repr(df) == expected

0 comments on commit 7961b1c

Please sign in to comment.