Skip to content

BUG: inconsistent creation of IntegerArray from boolean values #31104

Closed
@jorisvandenbossche

Description

@jorisvandenbossche

When creating a nullable integer array from boolean values, we are being inconsistent between a boolean numpy array and a object array with bools:

>>> pd.array(np.array([True, False]), dtype="Int64")  
<IntegerArray>
[1, 0]
Length: 2, dtype: Int64

>>> pd.array(np.array([True, False], dtype=object), dtype="Int64")  
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-33-bc23b09ea959> in <module>
----> 1 pd.array(np.array([True, False], dtype=object), dtype="Int64")

~/scipy/pandas/pandas/core/construction.py in array(data, dtype, copy)
    282     if is_extension_array_dtype(dtype):
    283         cls = cast(ExtensionDtype, dtype).construct_array_type()
--> 284         return cls._from_sequence(data, dtype=dtype, copy=copy)
    285 
    286     if dtype is None:

~/scipy/pandas/pandas/core/arrays/integer.py in _from_sequence(cls, scalars, dtype, copy)
    346     @classmethod
    347     def _from_sequence(cls, scalars, dtype=None, copy=False):
--> 348         return integer_array(scalars, dtype=dtype, copy=copy)
    349 
    350     @classmethod

~/scipy/pandas/pandas/core/arrays/integer.py in integer_array(values, dtype, copy)
    127     TypeError if incompatible types
    128     """
--> 129     values, mask = coerce_to_array(values, dtype=dtype, copy=copy)
    130     return IntegerArray(values, mask)
    131 

~/scipy/pandas/pandas/core/arrays/integer.py in coerce_to_array(values, dtype, mask, copy)
    210             "mixed-integer-float",
    211         ]:
--> 212             raise TypeError(f"{values.dtype} cannot be converted to an IntegerDtype")
    213 
    214     elif is_bool_dtype(values) and is_integer_dtype(dtype):

TypeError: object cannot be converted to an IntegerDtype

Metadata

Metadata

Assignees

No one assigned

    Labels

    ConstructorsSeries/DataFrame/Index/pd.array ConstructorsExtensionArrayExtending pandas with custom dtypes or arrays.NA - MaskedArraysRelated to pd.NA and nullable extension arraysNeeds TestsUnit test(s) needed to prevent regressionsgood first issue

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions