Skip to content

BUG: repr of np.datetime64('NaT') in Series/DataFrame with dtype object #25445

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Mar 30, 2019
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v0.25.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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`)
-
-

Expand Down
13 changes: 9 additions & 4 deletions pandas/io/formats/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from pandas._libs import lib
from pandas._libs.tslib import format_array_from_datetime
from pandas._libs.tslibs import NaT, Timedelta, Timestamp, iNaT
from pandas._libs.tslibs.nattype import is_np_nat
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this needs to be removed

from pandas.compat import StringIO, lzip

from pandas.core.dtypes.common import (
Expand Down Expand Up @@ -941,10 +942,14 @@ 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:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you add a comment here on what is going on here

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)
Expand Down
8 changes: 8 additions & 0 deletions pandas/tests/frame/test_repr_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -512,3 +512,11 @@ 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):
result = repr(box([arg('NaT')], dtype=object))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you add the issue number

assert result == expected