From 74589df479dc6471ba18ec40b68260347c6dd049 Mon Sep 17 00:00:00 2001 From: Chang She Date: Wed, 30 May 2012 00:45:55 -0400 Subject: [PATCH 1/2] BUG: raise exception on NaT in DatetimeIndex.astype('O') #1340 --- pandas/tseries/index.py | 4 ++++ pandas/tseries/tests/test_timeseries.py | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py index 4fe9130c3a0d1..f760ac4faec5e 100644 --- a/pandas/tseries/index.py +++ b/pandas/tseries/index.py @@ -5,6 +5,7 @@ import numpy as np +from pandas.core.common import isnull from pandas.core.index import Index, Int64Index from pandas.tseries.frequencies import infer_freq, to_offset from pandas.tseries.offsets import DateOffset, generate_range, Tick @@ -513,6 +514,9 @@ def astype(self, dtype): dtype = np.dtype(dtype) if dtype == np.object_: + if isnull(self).any(): + msg = 'DatetimeIndex with NaT cannot be converted to object' + raise ValueError(msg) return self.asobject return Index.astype(self, dtype) diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py index 9a0d6e6490942..ec572e2268f13 100644 --- a/pandas/tseries/tests/test_timeseries.py +++ b/pandas/tseries/tests/test_timeseries.py @@ -910,6 +910,10 @@ def test_index_conversion(self): self.assertRaises(ValueError, DatetimeIndex, ['a', 'b', 'c', 'd']) + def test_object_convert_fail(self): + idx = DatetimeIndex([NaT]) + self.assertRaises(ValueError, idx.astype, 'O') + def test_setops_conversion_fail(self): index = self.frame.index From 956c8147208a1d9e894635033b0eaf11b102c928 Mon Sep 17 00:00:00 2001 From: Chang She Date: Thu, 31 May 2012 23:23:53 -0400 Subject: [PATCH 2/2] push exception down to asobject --- pandas/tseries/index.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py index f760ac4faec5e..e1b033eb88227 100644 --- a/pandas/tseries/index.py +++ b/pandas/tseries/index.py @@ -514,9 +514,6 @@ def astype(self, dtype): dtype = np.dtype(dtype) if dtype == np.object_: - if isnull(self).any(): - msg = 'DatetimeIndex with NaT cannot be converted to object' - raise ValueError(msg) return self.asobject return Index.astype(self, dtype) @@ -536,6 +533,12 @@ def asobject(self): """ Convert to Index of datetime objects """ + if isnull(self).any(): + msg = 'DatetimeIndex with NaT cannot be converted to object' + raise ValueError(msg) + return self._get_object_index() + + def _get_object_index(self): boxed_values = _dt_box_array(self.asi8, self.offset, self.tz) return Index(boxed_values, dtype=object) @@ -1013,7 +1016,7 @@ def normalize(self): return DatetimeIndex(new_values, freq='infer', name=self.name) def __iter__(self): - return iter(self.asobject) + return iter(self._get_object_index()) def searchsorted(self, key, side='left'): if isinstance(key, np.ndarray):