Skip to content

BUG/API: setting behavior inserting negative numbers in np.uint/nullable UInt Series #48867

Open
@mroeschke

Description

@mroeschke

Pandas version checks

  • I have checked that this issue has not already been reported.

  • I have confirmed this bug exists on the latest version of pandas.

  • I have confirmed this bug exists on the main branch of pandas.

Reproducible Example

In [22]: np.__version__
Out[22]: '1.23.1'

In [23]: arr = np.array([1], dtype=np.uint8)

In [24]: arr[0] = -1

In [25]: arr
Out[25]: array([255], dtype=uint8)

In [26]: ser =  pd.Series([1], dtype=np.uint8)

In [27]: ser.iloc[0] = -1

In [28]: ser
Out[28]:
0   -1
dtype: int16

In [30]: ser_nullable = pd.Series([1], dtype="UInt8")

In [31]: ser_nullable.iloc[0] = -1

In [32]: ser_nullable
Out[32]:
0    255
dtype: UInt8

Issue Description

  • Numpy currently returns an overflowed valued but may raise in the future with NEP 50 cc @seberg

  • Series with np.uint appears to upcast the type to support -1

  • Series with nullable UInt appears to return an overflowed value

Here are the corresponding construction behavior

In [33]: np.array([-1], dtype=np.uint8)
Out[33]: array([255], dtype=uint8)

In [34]: pd.Series([-1], dtype=np.uint8)
OverflowError: Trying to coerce negative values to unsigned integers

In [35]: pd.Series([-1], dtype="UInt8")
TypeError: Cannot cast array data from dtype('int64') to dtype('uint8') according to the rule 'safe'

The above exception was the direct cause of the following exception:

TypeError: cannot safely cast non-equivalent int64 to uint8

Expected Behavior

Not sure if the existing rules here are established, but maybe given construction raises shouldn't setting too?

Installed Versions

Numpy Version: '1.23.1'

Metadata

Metadata

Assignees

No one assigned

    Labels

    API - ConsistencyInternal Consistency of API/BehaviorBugIndexingRelated to indexing on series/frames, not to indexes themselvesNA - MaskedArraysRelated to pd.NA and nullable extension arrays

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions