diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst index 99b57e2427509..89e14074ae75b 100644 --- a/doc/source/whatsnew/v0.25.0.rst +++ b/doc/source/whatsnew/v0.25.0.rst @@ -395,7 +395,7 @@ Sparse Other ^^^^^ -- +- Bug in :class:`Series` and :class:`DataFrame` repr where ``np.datetime64('NaT')`` and ``np.timedelta64('NaT')`` with ``dtype=object`` would be represented as ``NaN`` (:issue:`25445`) - - diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index dbe6b282ce9c0..1d08d559cb33f 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -941,10 +941,16 @@ def _format_strings(self): def _format(x): if self.na_rep is not None and is_scalar(x) and isna(x): - if x is None: - return 'None' - elif x is NaT: - return 'NaT' + try: + # try block for np.isnat specifically + # determine na_rep if x is None or NaT-like + if x is None: + return 'None' + elif x is NaT or np.isnat(x): + return 'NaT' + except (TypeError, ValueError): + # np.isnat only handles datetime or timedelta objects + pass return self.na_rep elif isinstance(x, PandasObject): return '{x}'.format(x=x) diff --git a/pandas/tests/frame/test_repr_info.py b/pandas/tests/frame/test_repr_info.py index c77c9d9143e38..e4f0b4c6459ae 100644 --- a/pandas/tests/frame/test_repr_info.py +++ b/pandas/tests/frame/test_repr_info.py @@ -512,3 +512,12 @@ def test_repr_categorical_dates_periods(self): df = DataFrame({'dt': Categorical(dt), 'p': Categorical(p)}) assert repr(df) == exp + + @pytest.mark.parametrize('arg', [np.datetime64, np.timedelta64]) + @pytest.mark.parametrize('box, expected', [ + [Series, '0 NaT\ndtype: object'], + [DataFrame, ' 0\n0 NaT']]) + def test_repr_np_nat_with_object(self, arg, box, expected): + # GH 25445 + result = repr(box([arg('NaT')], dtype=object)) + assert result == expected