Skip to content

Index.__add__ OK but __sub__ not? #19369

Closed
@jbrockmendel

Description

@jbrockmendel
Member

Curious about why Index.__add__ tries does the natural thing but Index.__sub__ raises TypeError.

    def __add__(self, other):
        return Index(np.array(self) + other)

    def __radd__(self, other):
        return Index(other + np.array(self))

    __iadd__ = __add__

    def __sub__(self, other):
        raise TypeError("cannot perform __sub__ with this index type: "
                        "{typ}".format(typ=type(self)))

Activity

jreback

jreback commented on Jan 24, 2018

@jreback
Contributor

this is why comments are important!

add is concat

eg
Index(list(‘abc’)) + ‘d’

sub doesn’t make sense

jbrockmendel

jbrockmendel commented on Jan 24, 2018

@jbrockmendel
MemberAuthor

That seems pretty string-specific. Shouldn't the object-dtype try to broadcast the scalar operation?

pd.Index([1, 2, 3], dtype='o') + 1
pd.Index([1, 2, 3], dtype='o') - 1

The motivation here is in https://github.com/pandas-dev/pandas/blob/master/pandas/core/indexes/datetimes.py#L933

where _add_offset_array can use self.astype('O') + np.array(other) but _sub_offset_array has to use self.__class__(self.astype('O').values - np.array(other))

added
IndexingRelated to indexing on series/frames, not to indexes themselves
on Jan 24, 2018
added this to the 0.24.0 milestone on Jul 20, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    EnhancementIndexingRelated to indexing on series/frames, not to indexes themselves

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

      Development

      Participants

      @jreback@jbrockmendel@gfyoung

      Issue actions

        Index.__add__ OK but __sub__ not? · Issue #19369 · pandas-dev/pandas