Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Index.__add__ OK but __sub__ not? #19369

Closed
jbrockmendel opened this issue Jan 24, 2018 · 2 comments · Fixed by #21981
Closed

Index.__add__ OK but __sub__ not? #19369

jbrockmendel opened this issue Jan 24, 2018 · 2 comments · Fixed by #21981
Labels
Enhancement Indexing Related to indexing on series/frames, not to indexes themselves
Milestone

Comments

@jbrockmendel
Copy link
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)))
@jreback
Copy link
Contributor

jreback commented Jan 24, 2018

this is why comments are important!

add is concat

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

sub doesn’t make sense

@jbrockmendel
Copy link
Member Author

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))

@gfyoung gfyoung added the Indexing Related to indexing on series/frames, not to indexes themselves label Jan 24, 2018
@jreback jreback added this to the 0.24.0 milestone Jul 20, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Enhancement Indexing Related to indexing on series/frames, not to indexes themselves
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants