diff --git a/pandas/core/array_algos/take.py b/pandas/core/array_algos/take.py index 188725f003f1e..6acfd4e155b51 100644 --- a/pandas/core/array_algos/take.py +++ b/pandas/core/array_algos/take.py @@ -22,6 +22,7 @@ from pandas.core.dtypes.common import ( ensure_platform_int, is_1d_only_ea_obj, + is_interval_dtype, ) from pandas.core.dtypes.missing import na_value_for_dtype @@ -110,6 +111,9 @@ def take_nd( return arr.take( indexer, fill_value=fill_value, allow_fill=allow_fill, axis=axis ) + if arr.dtype.kind in "O" and is_interval_dtype(arr): + # # GH46297 Interval + return arr.take(indexer, allow_fill=allow_fill) return arr.take(indexer, fill_value=fill_value, allow_fill=allow_fill) diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 26569b571724d..778dcf336f39f 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -2281,6 +2281,13 @@ def to_native_types( results_converted.append(result.astype(object, copy=False)) return np.vstack(results_converted) + elif isinstance(values, (PeriodArray, IntervalArray)): + # GH46297 + values = np.array(values, dtype="object") + mask = isna(values) + values[mask] = na_rep + return values + elif values.dtype.kind == "f" and not is_sparse(values): # see GH#13418: no special formatting is desired at the # output (important for appropriate 'quoting' behaviour), diff --git a/pandas/tests/io/formats/test_to_csv.py b/pandas/tests/io/formats/test_to_csv.py index d3f8e27c47e98..a92fe2a2576f4 100644 --- a/pandas/tests/io/formats/test_to_csv.py +++ b/pandas/tests/io/formats/test_to_csv.py @@ -315,6 +315,17 @@ def test_to_csv_date_format_in_categorical(self): ser = ser.astype("category") assert ser.to_csv(index=False, date_format="%Y-%m-%d") == expected + def test_to_cvs_interval_format_in_categorical(self): + # GH#46297 + df = DataFrame(index=[0], columns=["a"]) + df.at[0, "a"] = pd.Interval( + pd.Timestamp("2020-01-01"), pd.Timestamp("2020-01-02") + ) + df["a"] = df["a"].astype("category") + result = df.to_csv(index=False, date_format="%Y-%m-%d") + expected = tm.convert_rows_list_to_csv_str(["a", '"(2020-01-01, 2020-01-02]"']) + assert result == expected + def test_to_csv_float_ea_float_format(self): # GH#45991 df = DataFrame({"a": [1.1, 2.02, pd.NA, 6.000006], "b": "c"})