Skip to content

BUG: codes array of a categorical Series is not writeable and prevents running __dlpack__() on __dataframe__() outputs #48393

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

Closed
ogrisel opened this issue Sep 5, 2022 · 10 comments
Labels
Bug Interchange Dataframe Interchange Protocol
Milestone

Comments

@ogrisel
Copy link
Contributor

ogrisel commented Sep 5, 2022

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 readonly type specialization in the Cython code of the categorical Series. Wrong, see: #48393 (comment)

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
@ogrisel ogrisel added Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Sep 5, 2022
@ogrisel
Copy link
Contributor Author

ogrisel commented Sep 5, 2022

BTW, the fact that __dlpack__ is not implemented for readonly arrays is already tracked here:

@ogrisel
Copy link
Contributor Author

ogrisel commented Sep 5, 2022

Note that the pandas pd.core.interchange.from_dataframe(df.__dataframe__()) roundtrip is not impacted by this because it uses its own ctypes-based mechanism to map the buffers to numpy arrays without going through np.from_dlpack:

  • kind, bit_width, _, _ = dtype
    column_dtype = _NP_DTYPES.get(kind, {}).get(bit_width, None)
    if column_dtype is None:
    raise NotImplementedError(f"Conversion for {dtype} is not yet supported.")
    # TODO: No DLPack yet, so need to construct a new ndarray from the data pointer
    # and size in the buffer plus the dtype on the column. Use DLPack as NumPy supports
    # it since https://github.com/numpy/numpy/pull/19083
    ctypes_type = np.ctypeslib.as_ctypes_type(column_dtype)
    data_pointer = ctypes.cast(
    buffer.ptr + (offset * bit_width // 8), ctypes.POINTER(ctypes_type)
    )
    if bit_width == 1:
    assert length is not None, "`length` must be specified for a bit-mask buffer."
    arr = np.ctypeslib.as_array(data_pointer, shape=(buffer.bufsize,))
    return bitmask_to_bool_ndarray(arr, length, first_byte_offset=offset % 8)
    else:
    return np.ctypeslib.as_array(
    data_pointer, shape=(buffer.bufsize // (bit_width // 8),)
    )

@jorisvandenbossche
Copy link
Member

jorisvandenbossche commented Sep 5, 2022

@ogrisel I missed a much simpler explanation of why the codes became non-writeable after the construction of the Categorical, and that is because the public property that exposes explicitly returns a non-writable view of the internal array (and so not related to the readonly in cython):

@property
def codes(self) -> np.ndarray:
"""
The category codes of this categorical.
Codes are an array of integers which are the positions of the actual
values in the categories array.
There is no setter, use the other categorical methods and the normal item
setter to change values in the categorical.
Returns
-------
ndarray[int]
A non-writable view of the `codes` array.
"""
v = self._codes.view()
v.flags.writeable = False
return v

So this is done on purpose, and already like that for many years.

It still blocks the usage of __dlpack__ on those buffers, though. So maybe specifically in the dataframe interchange protocol, we could ensure to use the internal writeable array instead? (until numpy addresses this)
(although there are also other potential reasons to end up getting a dataframe with readonly arrays, so the question for scikit-learn is whether you want to support that in general or not)

@ogrisel
Copy link
Contributor Author

ogrisel commented Sep 5, 2022

It still blocks the usage of __dlpack__ on those buffers, though. So maybe specifically in the dataframe interchange protocol, we could ensure to use the internal writeable array instead? (until numpy addresses this)

+1 for a quick workaround.

@ogrisel ogrisel changed the title BUG: codes array of a categorical Series is not writeable BUG: codes array of a categorical Series is not writeable and prevents running __dlpack__ on __dataframe__ outputs Sep 5, 2022
@ogrisel ogrisel changed the title BUG: codes array of a categorical Series is not writeable and prevents running __dlpack__ on __dataframe__ outputs BUG: codes array of a categorical Series is not writeable and prevents running __dlpack__() on __dataframe__() outputs Sep 5, 2022
@jorisvandenbossche jorisvandenbossche removed the Needs Triage Issue that has not been reviewed by a pandas team member label Sep 5, 2022
@jorisvandenbossche jorisvandenbossche added this to the 1.5 milestone Sep 5, 2022
@jorisvandenbossche jorisvandenbossche added the Interchange Dataframe Interchange Protocol label Sep 5, 2022
@rgommers
Copy link
Contributor

rgommers commented Sep 5, 2022

A workaround seems reasonable here - the __dataframe__ implementation here could use self._codes instead of self.codes.

A quick search says that there's only a couple of usages of flags.writeable in Pandas:

pandas/core/missing.py
527:        if not x.flags.writeable:
529:        if not y.flags.writeable:
531:        if not new_x.flags.writeable:

pandas/core/arrays/categorical.py
782:        v.flags.writeable = False

pandas/core/indexes/multi.py
1338:                assert not level_codes.flags.writeable  # i.e. copy is needed
3957:    array_like.flags.writeable = False

The missing.py ones are all like:

if not x.flags.writeable:
    x = x.copy()

and the multi.py ones are one copy() and one creating of a readonly array - but on an index object, so shouldn't be relevant.

So I think that .codes should be the only problematic one here.

@datapythonista
Copy link
Member

@jorisvandenbossche do you think this should be a blocker for the 1.5 release planned for this week (I see you set the milestone)?

@jorisvandenbossche
Copy link
Member

It's certainly not a blocker, but given this is a new feature in 1.5, I certainly consider it a useful fix for 1.5 (or 1.5.x), so would like to somehow track that through the milestones.

@jorisvandenbossche
Copy link
Member

It's also only a tiny change, so quickly opened #48419

@datapythonista
Copy link
Member

Cool, makes sense, thanks for the clarification!

@mroeschke
Copy link
Member

Doesn't look like merging #48419 didn't close this issue for some reason, so doing so manually.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug Interchange Dataframe Interchange Protocol
Projects
None yet
Development

No branches or pull requests

5 participants