Skip to content

Avoid LossySetitemError on pandas >= 3.0#368

Open
marksteward wants to merge 1 commit into
daavoo:mainfrom
marksteward:main
Open

Avoid LossySetitemError on pandas >= 3.0#368
marksteward wants to merge 1 commit into
daavoo:mainfrom
marksteward:main

Conversation

@marksteward

@marksteward marksteward commented Jun 28, 2026

Copy link
Copy Markdown

Pandas 3.0 gets upset at assigning float-like values to a uint column when using .loc:

>>> import pandas as pd
>>> df = pd.DataFrame({"a": [1,  2,  3], "b": [4, 5, 6]}, dtype="uint16")
>>> df.loc[:, ["a", "b"]] *= 2  # fine
>>> df.loc[:, ["a", "b"]] /= 2  # uh oh
...
  File "/usr/local/lib/python3.12/site-packages/pandas/core/dtypes/cast.py", line 1725, in np_can_hold_element
    raise LossySetitemError
pandas.errors.LossySetitemError

The above exception was the direct cause of the following exception:
...
TypeError: Invalid value '0    1.0
1    2.0
2    3.0
Name: a, dtype: float64' for dtype 'uint16'

I've replaced this with an explicit integer division.

@marksteward marksteward marked this pull request as draft June 28, 2026 01:17
@marksteward marksteward marked this pull request as ready for review June 28, 2026 01:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant