Skip to content

Commit

Permalink
BUG: Fix inserting TImedelta into Series, closes pandas-dev#22717
Browse files Browse the repository at this point in the history
  • Loading branch information
jbrockmendel committed Jul 9, 2019
1 parent c64c9cb commit 864c32b
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
21 changes: 17 additions & 4 deletions pandas/core/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
is_scalar,
is_sequence,
is_sparse,
is_timedelta64_dtype,
)
from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries
from pandas.core.dtypes.missing import _infer_fill_value, isna
Expand Down Expand Up @@ -429,11 +430,23 @@ def _setitem_with_indexer(self, indexer, value):
# this preserves dtype of the value
new_values = Series([value])._values
if len(self.obj._values):
try:
new_values = np.concatenate([self.obj._values, new_values])
except TypeError:
if is_timedelta64_dtype(
new_values
) and not is_timedelta64_dtype(self.obj):
# GH#22717 np.concatenate incorrect casts
# timedelta64 to integer
as_obj = self.obj.astype(object)
new_values = np.concatenate([as_obj, new_values])
new_values = np.concatenate(
[as_obj, np.array([value], dtype=object)]
)
else:
try:
new_values = np.concatenate(
[self.obj._values, new_values]
)
except TypeError:
as_obj = self.obj.astype(object)
new_values = np.concatenate([as_obj, new_values])
self.obj._data = self.obj._constructor(
new_values, index=new_index, name=self.obj.name
)._data
Expand Down
9 changes: 9 additions & 0 deletions pandas/tests/series/indexing/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -653,6 +653,15 @@ def test_timedelta_assignment():
expected.loc[[1, 2, 3]] = pd.Timedelta(np.timedelta64(20, "m"))
tm.assert_series_equal(s, expected)

# GH#22717 inserting a Timedelta should _not_ cast to int64
ser = pd.Series(["x"])
ser["td"] = pd.Timedelta("9 days")
assert isinstance(ser["td"], pd.Timedelta)

ser = pd.Series(["x"])
ser.loc["td"] = pd.Timedelta("9 days")
assert isinstance(ser["td"], pd.Timedelta)


def test_underlying_data_conversion():
# GH 4080
Expand Down

0 comments on commit 864c32b

Please sign in to comment.