Skip to content

Commit 155af2c

Browse files
authored
BUG: astype('category') on dataframe backed by non-writeable arrays raises ValueError (#53678)
1 parent 89cb139 commit 155af2c

File tree

3 files changed

+11
-1
lines changed

3 files changed

+11
-1
lines changed

doc/source/whatsnew/v2.1.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -349,6 +349,7 @@ Bug fixes
349349

350350
Categorical
351351
^^^^^^^^^^^
352+
- Bug in :meth:`Series.astype` with ``dtype="category"`` for nullable arrays with read-only null value masks (:issue:`53658`)
352353
- Bug in :meth:`Series.map` , where the value of the ``na_action`` parameter was not used if the series held a :class:`Categorical` (:issue:`22527`).
353354
-
354355

pandas/_libs/hashtable_class_helper.pxi.in

+1-1
Original file line numberDiff line numberDiff line change
@@ -648,7 +648,7 @@ cdef class {{name}}HashTable(HashTable):
648648
UInt8Vector result_mask
649649
UInt8VectorData *rmd
650650
bint use_na_value, use_mask, seen_na = False
651-
uint8_t[:] mask_values
651+
const uint8_t[:] mask_values
652652

653653
if return_inverse:
654654
labels = np.empty(n, dtype=np.intp)

pandas/tests/extension/test_categorical.py

+9
Original file line numberDiff line numberDiff line change
@@ -319,3 +319,12 @@ def test_repr_2d(self, data):
319319

320320
res = repr(data.reshape(-1, 1))
321321
assert res.count("\nCategories") == 1
322+
323+
324+
def test_astype_category_readonly_mask_values():
325+
# GH 53658
326+
df = pd.DataFrame([0, 1, 2], dtype="Int64")
327+
df._mgr.arrays[0]._mask.flags["WRITEABLE"] = False
328+
result = df.astype("category")
329+
expected = pd.DataFrame([0, 1, 2], dtype="Int64").astype("category")
330+
tm.assert_frame_equal(result, expected)

0 commit comments

Comments
 (0)