8000 Merge pull request #6033 from pitrou/td64_array_repr · njsmith/numpy@61d2a44 · GitHub
[go: up one dir, main page]

Skip to content

Commit 61d2a44

Browse files
committed
Merge pull request numpy#6033 from pitrou/td64_array_repr
ENH: improve string representation of NaTs in timedelta64 arrays
2 parents 23e10e1 + 7aa4f49 commit 61d2a44

File tree

2 files changed

+29
-5
lines changed

2 files changed

+29
-5
lines changed

numpy/core/arrayprint.py

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@
1919
from functools import reduce
2020
from . import numerictypes as _nt
2121
from .umath import maximum, minimum, absolute, not_equal, isnan, isinf
22-
from .multiarray import format_longfloat, datetime_as_string, datetime_data
22+
from .multiarray import (array, format_longfloat, datetime_as_string,
23+
datetime_data)
2324
from .fromnumeric import ravel
2425
from .numeric import asarray
2526

@@ -733,10 +734,22 @@ def __call__(self, x):
733734
class TimedeltaFormat(object):
734735
def __init__(self, data):
735736
if data.dtype.kind == 'm':
736-
v = data.view('i8')
737-
max_str_len = max(len(str(maximum.reduce(v))),
738-
len(str(minimum.reduce(v))))
737+
nat_value = array(['NaT'], dtype=data.dtype)[0]
738+
v = data[not_equal(data, nat_value)].view('i8')
739+
if len(v) > 0:
740+
# Max str length of non-NaT elements
741+
max_str_len = max(len(str(maximum.reduce(v))),
742+
len(str(minimum.reduce(v))))
743+
else:
744+
max_str_len = 0
745+
if len(v) < len(data):
746+
# data contains a NaT
747+
max_str_len = max(max_str_len, 5)
739748
self.format = '%' + str(max_str_len) + 'd'
749+
self._nat = "'NaT'".rjust(max_str_len)
740750

741751
def __call__(self, x):
742-
return self.format % x.astype('i8')
752+
if x + 1 == x:
753+
return self._nat
754+
else:
755+
return self.format % x.astype('i8')

numpy/core/tests/test_datetime.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -530,6 +530,17 @@ def test_datetime_array_str(self):
530530
a = np.array(['2010', 'NaT', '2030']).astype('M')
531531
assert_equal(str(a), "['2010' 'NaT' '2030']")
532532

533+
def test_timedelta_array_str(self):
534+
a = np.array([-1, 0, 100], dtype='m')
535+
assert_equal(str(a), "[ -1 0 100]")
536+
a = np.array(['NaT', 'NaT'], dtype='m')
537+
assert_equal(str(a), "['NaT' 'NaT']")
538+
# Check right-alignment with NaTs
539+
a = np.array([-1, 'NaT', 0], dtype='m')
540+
assert_equal(str(a), "[ -1 'NaT' 0]")
541+
a = np.array([-1, 'NaT', 1234567], dtype='m')
542+
assert_equal(str(a), "[ -1 'NaT' 1234567]")
543+
533544
def test_pickle(self):
534545
# Check that pickle roundtripping works
535546
dt = np.dtype('M8[7D]')

0 commit comments

Comments
 (0)
0