Skip to content

BUG: pickle Index[object] preserve dtype #43188

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 3 commits into from
Sep 4, 2021
Merged
Show file tree
Hide file tree
Changes from 2 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
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.4.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,7 @@ I/O
- Bug in :func:`json_normalize` where ``errors=ignore`` could fail to ignore missing values of ``meta`` when ``record_path`` has a length greater than one (:issue:`41876`)
- Bug in :func:`read_csv` with multi-header input and arguments referencing column names as tuples (:issue:`42446`)
- Bug in :func:`Series.to_json` and :func:`DataFrame.to_json` where some attributes were skipped when serialising plain Python objects to JSON (:issue:`42768`, :issue:`33043`)
-
- Bug in unpickling a :class:`Index` with object dtype incorrectly inferring numeric dtypes (:issue:`43188`)

Period
^^^^^^
Expand Down
4 changes: 4 additions & 0 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,10 @@ def _new_Index(cls, d):
# GH#23752 "labels" kwarg has been replaced with "codes"
d["codes"] = d.pop("labels")

elif "dtype" not in d and "data" in d:
# Prevent Index.__new__ from conducting inference;
# "data" key not in RangeIndex
d["dtype"] = d["data"].dtype
return cls.__new__(cls, **d)


Expand Down
11 changes: 11 additions & 0 deletions pandas/tests/indexes/base_class/test_pickle.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from pandas import Index
import pandas._testing as tm


def test_pickle_preserves_object_dtype():
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you paramterize on all the index types? (i think we have a fixture)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we can come back and add more tests that use the fixture, but id like to keep this test targeted at a specific bug

# GH#43188, GH#43155 don't infer numeric dtype
index = Index([1, 2, 3], dtype=object)

result = tm.round_trip_pickle(index)
assert result.dtype == object
tm.assert_index_equal(index, result)