Skip to content

Commit eb920f9

Browse files
committed
BUG: CategoricalIndex.format
1 parent 6302f7b commit eb920f9

File tree

3 files changed

+16
-6
lines changed

3 files changed

+16
-6
lines changed

doc/source/whatsnew/v1.1.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -1095,6 +1095,7 @@ I/O
10951095
- Bug in :func:`read_excel` where datetime values are used in the header in a :class:`MultiIndex` (:issue:`34748`)
10961096
- :func:`read_excel` no longer takes ``**kwds`` arguments. This means that passing in the keyword argument ``chunksize`` now raises a ``TypeError`` (previously raised a ``NotImplementedError``), while passing in the keyword argument ``encoding`` now raises a ``TypeError`` (:issue:`34464`)
10971097
- Bug in :meth:`DataFrame.to_records` was incorrectly losing timezone information in timezone-aware ``datetime64`` columns (:issue:`32535`)
1098+
- Bug in :meth:`DataFrame.to_string` when :attr:`DataFrame.columns` is a :class:`CategoricalIndex` (:issue:`35439`)
10981099

10991100
Plotting
11001101
^^^^^^^^

pandas/core/indexes/category.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
pandas_dtype,
2121
)
2222
from pandas.core.dtypes.dtypes import CategoricalDtype
23-
from pandas.core.dtypes.missing import is_valid_nat_for_dtype, isna
23+
from pandas.core.dtypes.missing import is_valid_nat_for_dtype, isna, notna
2424

2525
from pandas.core import accessor
2626
from pandas.core.algorithms import take_1d
@@ -348,12 +348,12 @@ def _format_attrs(self):
348348
return attrs
349349

350350
def _format_with_header(self, header, na_rep="NaN") -> List[str]:
351-
from pandas.io.formats.format import format_array
351+
from pandas.io.formats.printing import pprint_thing
352352

353-
formatted_values = format_array(
354-
self._values, formatter=None, na_rep=na_rep, justify="left"
355-
)
356-
result = ibase.trim_front(formatted_values)
353+
result = [
354+
pprint_thing(x, escape_chars=("\t", "\r", "\n")) if notna(x) else na_rep
355+
for x in self._values
356+
]
357357
return header + result
358358

359359
# --------------------------------------------------------------------

pandas/tests/io/formats/test_format.py

+9
Original file line numberDiff line numberDiff line change
@@ -2141,6 +2141,15 @@ def test_dict_entries(self):
21412141
assert "'a': 1" in val
21422142
assert "'b': 2" in val
21432143

2144+
def test_categorical_columns(self):
2145+
# GH35439
2146+
data = [[4, 2], [3, 2], [4, 3]]
2147+
cols = ["aaaaaaaaa", "b"]
2148+
df = pd.DataFrame(data, columns=cols)
2149+
df_cat_cols = pd.DataFrame(data, columns=pd.CategoricalIndex(cols))
2150+
2151+
assert df.to_string() == df_cat_cols.to_string()
2152+
21442153
def test_period(self):
21452154
# GH 12615
21462155
df = pd.DataFrame(

0 commit comments

Comments
 (0)