Skip to content

Commit 57995bf

Browse files
mortadaJulianWgs
authored andcommitted
BUG: fix TypeError when looking up a str subclass on a DataFrame with DatetimeIndex (pandas-dev#37366) (pandas-dev#41406)
1 parent c3e0a0b commit 57995bf

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/indexing.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -2289,7 +2289,7 @@ def convert_to_index_sliceable(obj: DataFrame, key):
22892289
# slice here via partial string indexing
22902290
if idx._supports_partial_string_indexing:
22912291
try:
2292-
res = idx._get_string_slice(key)
2292+
res = idx._get_string_slice(str(key))
22932293
warnings.warn(
22942294
"Indexing a DataFrame with a datetimelike index using a single "
22952295
"string to slice the rows, like `frame[string]`, is deprecated "

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)