Skip to content

Commit 8c4d5dc

Browse files
committed
BUG: fix TypeError when looking up a str subclass on a DataFrame with DatetimeIndex (#37366)
1 parent 67c9385 commit 8c4d5dc

File tree

3 files changed

+15
-1
lines changed

3 files changed

+15
-1
lines changed

doc/source/whatsnew/v1.3.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -790,6 +790,7 @@ Indexing
790790
- Bug in :meth:`DataFrame.loc.__setitem__` when setting-with-expansion incorrectly raising when the index in the expanding axis contains duplicates (:issue:`40096`)
791791
- Bug in :meth:`DataFrame.loc` incorrectly matching non-boolean index elements (:issue:`20432`)
792792
- Bug in :meth:`Series.__delitem__` with ``ExtensionDtype`` incorrectly casting to ``ndarray`` (:issue:`40386`)
793+
- Bug in :meth:`DataFrame.__setitem__` raising ``TypeError`` when using a str subclass as the column name with a :class:`DatetimeIndex` (:issue:`37366`)
793794

794795
Missing
795796
^^^^^^^

pandas/core/indexes/datetimes.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -771,7 +771,7 @@ def _maybe_cast_slice_bound(self, label, side: str, kind):
771771

772772
def _get_string_slice(self, key: str):
773773
freq = getattr(self, "freqstr", getattr(self, "inferred_freq", None))
774-
parsed, reso_str = parsing.parse_time_string(key, freq)
774+
parsed, reso_str = parsing.parse_time_string(str(key), freq)
775775
reso = Resolution.from_attrname(reso_str)
776776
return self._partial_date_slice(reso, parsed)
777777

pandas/tests/indexing/test_datetime.py

+13
Original file line numberDiff line numberDiff line change
@@ -152,3 +152,16 @@ def test_getitem_millisecond_resolution(self, frame_or_series):
152152
],
153153
)
154154
tm.assert_equal(result, expected)
155+
156+
def test_str_subclass(self):
157+
# GH 37366
158+
class mystring(str):
159+
pass
160+
161+
data = ["2020-10-22 01:21:00+00:00"]
162+
index = pd.DatetimeIndex(data)
163+
df = DataFrame({"a": [1]}, index=index)
164+
df["b"] = 2
165+
df[mystring("c")] = 3
166+
expected = DataFrame({"a": [1], "b": [2], mystring("c"): [3]}, index=index)
167+
tm.assert_equal(df, expected)

0 commit comments

Comments
 (0)