Skip to content

BUG: fix TypeError when looking up a str subclass on a DataFrame with… #41406

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 1 commit into from
May 10, 2021
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/whatsnew/v1.3.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -790,6 +790,7 @@ Indexing
- Bug in :meth:`DataFrame.loc.__setitem__` when setting-with-expansion incorrectly raising when the index in the expanding axis contains duplicates (:issue:`40096`)
- Bug in :meth:`DataFrame.loc` incorrectly matching non-boolean index elements (:issue:`20432`)
- Bug in :meth:`Series.__delitem__` with ``ExtensionDtype`` incorrectly casting to ``ndarray`` (:issue:`40386`)
- Bug in :meth:`DataFrame.__setitem__` raising ``TypeError`` when using a str subclass as the column name with a :class:`DatetimeIndex` (:issue:`37366`)

Missing
^^^^^^^
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -2289,7 +2289,7 @@ def convert_to_index_sliceable(obj: DataFrame, key):
# slice here via partial string indexing
if idx._supports_partial_string_indexing:
try:
res = idx._get_string_slice(key)
res = idx._get_string_slice(str(key))
warnings.warn(
"Indexing a DataFrame with a datetimelike index using a single "
"string to slice the rows, like `frame[string]`, is deprecated "
Expand Down
13 changes: 13 additions & 0 deletions pandas/tests/indexing/test_datetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,3 +152,16 @@ def test_getitem_millisecond_resolution(self, frame_or_series):
],
)
tm.assert_equal(result, expected)

def test_str_subclass(self):
# GH 37366
class mystring(str):
pass

data = ["2020-10-22 01:21:00+00:00"]
index = pd.DatetimeIndex(data)
df = DataFrame({"a": [1]}, index=index)
df["b"] = 2
df[mystring("c")] = 3
expected = DataFrame({"a": [1], "b": [2], mystring("c"): [3]}, index=index)
tm.assert_equal(df, expected)