Skip to content

Support numpy ufuncs for ExtensionArrays #22798

Closed
@jorisvandenbossche

Description

@jorisvandenbossche

Currently calling numpy ufuncs such as np.exp on a Series[EA] or EA does not work yet:

In [44]: s = pd.Series([1, 2, 3, 4], dtype='Int64')

In [45]: np.exp(s)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-45-fb7258693ae9> in <module>()
----> 1 np.exp(s)

~/scipy/pandas/pandas/core/series.py in __array_prepare__(self, result, context)
    671                                 obj=type(obj).__name__,
    672                                 dtype=getattr(obj, 'dtype', None),
--> 673                                 op=context[0].__name__))
    674         return result
    675 

TypeError: Series with dtype Int64 cannot perform the numpy op exp

In [46]: np.exp(s.values)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-46-69f0b0471ea8> in <module>()
----> 1 np.exp(s.values)

AttributeError: 'int' object has no attribute 'exp'

In [47]: np.exp(s.astype(int))   # but works for numpy dtyped series
Out[47]: 
0     2.718282
1     7.389056
2    20.085537
3    54.598150
dtype: float64

I think it would be nice to have this working, and without looking in detail into it, I would assume the best way to go is to actually support the __array_ufunc__ protocol on ExtensionArrays itself and to ensure Series then properly uses that?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions