Skip to content

Commit 2173680

Browse files
committed
BUG: Fix DatetimeIndex.insert() with non-datetimes.
Coerces to object Index instead.
1 parent 1dda3fb commit 2173680

File tree

3 files changed

+29
-3
lines changed

3 files changed

+29
-3
lines changed

pandas/tests/test_frame.py

+13
Original file line numberDiff line numberDiff line change
@@ -10897,6 +10897,19 @@ def test_reset_index_multiindex_col(self):
1089710897
['a', 'mean', 'median', 'mean']])
1089810898
assert_frame_equal(rs, xp)
1089910899

10900+
def test_reset_index_with_datetimeindex_cols(self):
10901+
# GH5818
10902+
#
10903+
df = pd.DataFrame([[1, 2], [3, 4]],
10904+
columns=pd.date_range('1/1/2013', '1/2/2013'),
10905+
index=['A', 'B'])
10906+
10907+
result = df.reset_index()
10908+
expected = pd.DataFrame([['A', 1, 2], ['B', 3, 4]],
10909+
columns=['index', datetime(2013, 1, 1),
10910+
datetime(2013, 1, 2)])
10911+
assert_frame_equal(result, expected)
10912+
1090010913
#----------------------------------------------------------------------
1090110914
# Tests to cope with refactored internals
1090210915
def test_as_matrix_numeric_cols(self):

pandas/tseries/index.py

+9-3
Original file line numberDiff line numberDiff line change
@@ -1533,18 +1533,24 @@ def insert(self, loc, item):
15331533
----------
15341534
loc : int
15351535
item : object
1536+
if not either a Python datetime or a numpy integer-like, returned
1537+
Index dtype will be object rather than datetime.
15361538
15371539
Returns
15381540
-------
15391541
new_index : Index
15401542
"""
15411543
if isinstance(item, datetime):
15421544
item = _to_m8(item, tz=self.tz)
1543-
1544-
new_index = np.concatenate((self[:loc].asi8,
1545+
try:
1546+
new_index = np.concatenate((self[:loc].asi8,
15451547
[item.view(np.int64)],
15461548
self[loc:].asi8))
1547-
return DatetimeIndex(new_index, freq='infer')
1549+
return DatetimeIndex(new_index, freq='infer')
1550+
except (AttributeError, TypeError):
1551+
# fall back to object index
1552+
return self.asobject.insert(loc, item)
1553+
15481554

15491555
def delete(self, loc):
15501556
"""

pandas/tseries/tests/test_timeseries.py

+7
Original file line numberDiff line numberDiff line change
@@ -2099,6 +2099,13 @@ def test_insert(self):
20992099
'2000-01-02'])
21002100
self.assert_(result.equals(exp))
21012101

2102+
# insertion of non-datetime should coerce to object index
2103+
result = idx.insert(1, 'inserted')
2104+
expected = Index([datetime(2000, 1, 4), 'inserted', datetime(2000, 1, 1),
2105+
datetime(2000, 1, 2)])
2106+
self.assert_(not isinstance(result, DatetimeIndex))
2107+
tm.assert_index_equal(result, expected)
2108+
21022109
idx = date_range('1/1/2000', periods=3, freq='M')
21032110
result = idx.insert(3, datetime(2000, 4, 30))
21042111
self.assert_(result.freqstr == 'M')

0 commit comments

Comments
 (0)