BUG: codes
array of a categorical Series is not writeable and prevents running __dlpack__()
on __dataframe__()
outputs · Issue #48393 · pandas-dev/pandas (original) (raw)
Reproducible Example
import pandas as pd df = pd.DataFrame({"a_int": [1, 2, 3]}) df["a_cat"] = df["a_int"].astype("category")
df["a_int"].values.flags.writeable True
df["a_cat"].values.codes.flags.writeable False
Issue Description
Speaking with @jorisvandenbossche, it seems that this is not intentional and might be caused by the used of the Wrong, see: #48393 (comment)readonly
type specialization in the Cython code of the categorical Series.
The fact that this is not writeable makes it impossible to leverage the __dlpack__()
method of the buffers returned by the __dataframe__()
interop method because under the hood it would result in calling:
import numpy as np np.from_dlpack(df.dataframe().get_column_by_name("a_cat").get_buffers()['data'][0]) Traceback (most recent call last): Input In [6] in <cell line: 1> np.from_dlpack(df.dataframe().get_column_by_name("a_cat").get_buffers()['data'][0]) File ~/code/pandas/pandas/core/interchange/buffer.py:57 in dlpack return self._x.dlpack() TypeError: NumPy currently only supports dlpack for writeable arrays
Expected Behavior
Have the .codes
array be writeable, even if the .codes attribute itself is not mutable in the Cython class.
Installed Versions
INSTALLED VERSIONS
------------------
commit : 298dac384f92726b6da9a6319695cb0269e6eeb8
python : 3.10.6.final.0
python-bits : 64
OS : Darwin
OS-release : 21.4.0
Version : Darwin Kernel Version 21.4.0: Fri Mar 18 00:47:26 PDT 2022; root:xnu-8020.101.4~15/RELEASE_ARM64_T8101
machine : arm64
processor : arm
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : None.UTF-8
pandas : 1.6.0.dev0+49.g298dac384f
numpy : 1.23.2
pytz : 2022.2.1
dateutil : 2.8.2
setuptools : 65.3.0
pip : 22.2.2
Cython : 0.29.32
pytest : 7.1.2
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 3.1.2
IPython : 8.4.0
pandas_datareader: None
bs4 : 4.11.1
bottleneck : None
brotli : None
fastparquet : None
fsspec : None
gcsfs : None
matplotlib : 3.5.3
numba : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pyreadstat : None
pyxlsb : None
s3fs : None
scipy : 1.9.1
snappy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
xlwt : None
zstandard : None
tzdata : None