Skip to content

BUG: Fix DatetimeIndex.insert() with strings. #5819

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
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/release.rst
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ Bug Fixes
~~~~~~~~~
- Bug in Series replace with timestamp dict (:issue:`5797`)
- read_csv/read_table now respects the `prefix` kwarg (:issue:`5732`).
- Bug with insert of strings into DatetimeIndex (:issue:`5818`, :issue:`5819`)

pandas 0.13.0
-------------
Expand Down
1 change: 0 additions & 1 deletion pandas/core/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1455,7 +1455,6 @@ def _safe_append_to_index(index, key):

# raise here as this is basically an unsafe operation and we want
# it to be obvious that you are doing something wrong

raise ValueError("unsafe appending to index of type {0} with a key "
"{1}".format(index.__class__.__name__, key))

Expand Down
6 changes: 4 additions & 2 deletions pandas/sparse/tests/test_sparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -1084,8 +1084,10 @@ def test_icol(self):

def test_set_value(self):

# this is invalid because it is not a valid type for this index
self.assertRaises(ValueError, self.frame.set_value, 'foobar', 'B', 1.5)
# ok as the index gets conver to object
frame = self.frame.copy()
res = frame.set_value('foobar', 'B', 1.5)
self.assert_(res.index.dtype == 'object')

res = self.frame
res.index = res.index.astype(object)
Expand Down
13 changes: 13 additions & 0 deletions pandas/tests/test_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -10897,6 +10897,19 @@ def test_reset_index_multiindex_col(self):
['a', 'mean', 'median', 'mean']])
assert_frame_equal(rs, xp)

def test_reset_index_with_datetimeindex_cols(self):
# GH5818
#
df = pd.DataFrame([[1, 2], [3, 4]],
columns=pd.date_range('1/1/2013', '1/2/2013'),
index=['A', 'B'])

result = df.reset_index()
expected = pd.DataFrame([['A', 1, 2], ['B', 3, 4]],
columns=['index', datetime(2013, 1, 1),
datetime(2013, 1, 2)])
assert_frame_equal(result, expected)

#----------------------------------------------------------------------
# Tests to cope with refactored internals
def test_as_matrix_numeric_cols(self):
Expand Down
7 changes: 4 additions & 3 deletions pandas/tests/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1665,15 +1665,13 @@ def test_partial_set_invalid(self):

df = tm.makeTimeDataFrame()

# don't allow not string inserts
def f():
df.loc[100.0, :] = df.ix[0]
self.assertRaises(ValueError, f)
def f():
df.loc[100,:] = df.ix[0]
self.assertRaises(ValueError, f)
def f():
df.loc['a',:] = df.ix[0]
self.assertRaises(ValueError, f)

def f():
df.ix[100.0, :] = df.ix[0]
Expand All @@ -1682,6 +1680,9 @@ def f():
df.ix[100,:] = df.ix[0]
self.assertRaises(ValueError, f)

# allow object conversion here
df.loc['a',:] = df.ix[0]

def test_partial_set_empty(self):

# GH5226
Expand Down
16 changes: 12 additions & 4 deletions pandas/tseries/index.py
Original file line number Diff line number Diff line change
Expand Up @@ -1533,18 +1533,26 @@ def insert(self, loc, item):
----------
loc : int
item : object
if not either a Python datetime or a numpy integer-like, returned
Index dtype will be object rather than datetime.

Returns
-------
new_index : Index
"""
if isinstance(item, datetime):
item = _to_m8(item, tz=self.tz)

new_index = np.concatenate((self[:loc].asi8,
try:
new_index = np.concatenate((self[:loc].asi8,
[item.view(np.int64)],
self[loc:].asi8))
return DatetimeIndex(new_index, freq='infer')
return DatetimeIndex(new_index, freq='infer')
except (AttributeError, TypeError):

# fall back to object index
if isinstance(item,compat.string_types):
return self.asobject.insert(loc, item)
raise TypeError("cannot insert DatetimeIndex with incompatible label")

def delete(self, loc):
"""
Expand Down Expand Up @@ -1585,7 +1593,7 @@ def tz_convert(self, tz):
def tz_localize(self, tz, infer_dst=False):
"""
Localize tz-naive DatetimeIndex to given time zone (using pytz)

Parameters
----------
tz : string or pytz.timezone
Expand Down
7 changes: 7 additions & 0 deletions pandas/tseries/tests/test_timeseries.py
Original file line number Diff line number Diff line change
Expand Up @@ -2099,6 +2099,13 @@ def test_insert(self):
'2000-01-02'])
self.assert_(result.equals(exp))

# insertion of non-datetime should coerce to object index
result = idx.insert(1, 'inserted')
expected = Index([datetime(2000, 1, 4), 'inserted', datetime(2000, 1, 1),
datetime(2000, 1, 2)])
self.assert_(not isinstance(result, DatetimeIndex))
tm.assert_index_equal(result, expected)

idx = date_range('1/1/2000', periods=3, freq='M')
result = idx.insert(3, datetime(2000, 4, 30))
self.assert_(result.freqstr == 'M')
Expand Down