Skip to content

Commit cb89bc0

Browse files
mroeschkejreback
authored andcommitted
BUG: repr of np.datetime64('NaT') in Series/DataFrame with dtype object (#25445)
1 parent 025b5dc commit cb89bc0

File tree

3 files changed

+20
-5
lines changed

3 files changed

+20
-5
lines changed

doc/source/whatsnew/v0.25.0.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -395,7 +395,7 @@ Sparse
395395
Other
396396
^^^^^
397397

398-
-
398+
- 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`)
399399
-
400400
-
401401

pandas/io/formats/format.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -952,10 +952,16 @@ def _format_strings(self):
952952

953953
def _format(x):
954954
if self.na_rep is not None and is_scalar(x) and isna(x):
955-
if x is None:
956-
return 'None'
957-
elif x is NaT:
958-
return 'NaT'
955+
try:
956+
# try block for np.isnat specifically
957+
# determine na_rep if x is None or NaT-like
958+
if x is None:
959+
return 'None'
960+
elif x is NaT or np.isnat(x):
961+
return 'NaT'
962+
except (TypeError, ValueError):
963+
# np.isnat only handles datetime or timedelta objects
964+
pass
959965
return self.na_rep
960966
elif isinstance(x, PandasObject):
961967
return '{x}'.format(x=x)

pandas/tests/frame/test_repr_info.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -512,3 +512,12 @@ def test_repr_categorical_dates_periods(self):
512512

513513
df = DataFrame({'dt': Categorical(dt), 'p': Categorical(p)})
514514
assert repr(df) == exp
515+
516+
@pytest.mark.parametrize('arg', [np.datetime64, np.timedelta64])
517+
@pytest.mark.parametrize('box, expected', [
518+
[Series, '0 NaT\ndtype: object'],
519+
[DataFrame, ' 0\n0 NaT']])
520+
def test_repr_np_nat_with_object(self, arg, box, expected):
521+
# GH 25445
522+
result = repr(box([arg('NaT')], dtype=object))
523+
assert result == expected

0 commit comments

Comments
 (0)