-
-
Notifications
You must be signed in to change notification settings - Fork 18.4k
[WIP] Add basic ExtensionIndex class #23223
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
Closed
Closed
Changes from 3 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
015e4b2
Add basic ExtensionIndex class
jorisvandenbossche 9e282c9
clean-up
jorisvandenbossche 24fc7fd
Merge remote-tracking branch 'upstream/master' into EAindex
jorisvandenbossche da23c1f
Merge remote-tracking branch 'upstream/master' into EAindex
jorisvandenbossche 6c1d798
more robust constructor + add tests
jorisvandenbossche 00d4a16
add common tests
jorisvandenbossche File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,149 @@ | ||
import numpy as np | ||
from pandas._libs import index as libindex | ||
|
||
# from pandas._libs import (lib, index as libindex, tslibs, | ||
# algos as libalgos, join as libjoin, | ||
# Timedelta) | ||
|
||
from pandas.compat.numpy import function as nv | ||
|
||
from pandas.core.arrays import ExtensionArray | ||
from pandas.core.dtypes.common import ( | ||
ensure_platform_int, | ||
is_integer_dtype, is_float_dtype) | ||
|
||
from pandas.util._decorators import ( | ||
Appender, cache_readonly) | ||
|
||
from .base import Index | ||
|
||
|
||
# _index_doc_kwargs = dict(ibase._index_doc_kwargs) | ||
# _index_doc_kwargs.update( | ||
# dict(klass='IntervalIndex', | ||
# target_klass='IntervalIndex or list of Intervals', | ||
# name=textwrap.dedent("""\ | ||
# name : object, optional | ||
# to be stored in the index. | ||
# """), | ||
# )) | ||
|
||
|
||
class ExtensionIndex(Index): | ||
""" | ||
Index class that holds an ExtensionArray. | ||
|
||
""" | ||
_typ = 'extensionindex' | ||
_comparables = ['name'] | ||
_attributes = ['name'] | ||
|
||
_can_hold_na = True | ||
|
||
@property | ||
def _is_numeric_dtype(self): | ||
return self.dtype._is_numeric | ||
|
||
# TODO | ||
# # would we like our indexing holder to defer to us | ||
# _defer_to_indexing = False | ||
|
||
# # prioritize current class for _shallow_copy_with_infer, | ||
# # used to infer integers as datetime-likes | ||
# _infer_as_myclass = False | ||
|
||
def __new__(cls, *args, **kwargs): | ||
return object.__new__(cls) | ||
|
||
def __init__(self, array, name=None, copy=False, **kwargs): | ||
# needs to accept and ignore kwargs eg for freq passed in | ||
# Index._shallow_copy_with_infer | ||
|
||
if isinstance(array, ExtensionIndex): | ||
array = array._data | ||
|
||
if not isinstance(array, ExtensionArray): | ||
raise TypeError() | ||
if copy: | ||
array = array.copy() | ||
self._data = array | ||
self.name = name | ||
|
||
def __len__(self): | ||
""" | ||
return the length of the Index | ||
""" | ||
return len(self._data) | ||
|
||
@property | ||
def size(self): | ||
# EA does not have .size | ||
return len(self._data) | ||
|
||
def __array__(self, dtype=None): | ||
""" the array interface, return my values """ | ||
return np.array(self._data) | ||
|
||
@cache_readonly | ||
def dtype(self): | ||
""" return the dtype object of the underlying data """ | ||
return self._values.dtype | ||
|
||
@cache_readonly | ||
def dtype_str(self): | ||
""" return the dtype str of the underlying data """ | ||
return str(self.dtype) | ||
|
||
@property | ||
def _values(self): | ||
return self._data | ||
|
||
@property | ||
def values(self): | ||
""" return the underlying data as an ndarray """ | ||
return self._values | ||
|
||
@cache_readonly | ||
def _isnan(self): | ||
""" return if each value is nan""" | ||
return self._values.isna() | ||
|
||
@cache_readonly | ||
def _engine_type(self): | ||
values, na_value = self._values._values_for_factorize() | ||
if is_integer_dtype(values): | ||
return libindex.Int64Engine | ||
elif is_float_dtype(values): | ||
return libindex.Float64Engine | ||
# TODO add more | ||
else: | ||
return libindex.ObjectEngine | ||
|
||
@cache_readonly | ||
def _engine(self): | ||
# property, for now, slow to look up | ||
values, na_value = self._values._values_for_factorize() | ||
return self._engine_type(lambda: values, len(self)) | ||
|
||
def _format_with_header(self, header, **kwargs): | ||
return header + list(self._format_native_types(**kwargs)) | ||
|
||
@Appender(Index.take.__doc__) | ||
def take(self, indices, axis=0, allow_fill=True, fill_value=None, | ||
**kwargs): | ||
if kwargs: | ||
nv.validate_take(tuple(), kwargs) | ||
indices = ensure_platform_int(indices) | ||
|
||
result = self._data.take(indices, allow_fill=allow_fill, | ||
fill_value=fill_value) | ||
attributes = self._get_attributes_dict() | ||
return self._simple_new(result, **attributes) | ||
|
||
def __getitem__(self, value): | ||
result = self._data[value] | ||
if isinstance(result, self._data.__class__): | ||
return self._shallow_copy(result) | ||
else: | ||
# scalar | ||
return result |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,96 @@ | ||
import pytest | ||
import numpy as np | ||
|
||
import pandas as pd | ||
import pandas.util.testing as tm | ||
from pandas.core.indexes.extension import ExtensionIndex | ||
|
||
from .base import BaseExtensionTests | ||
|
||
|
||
class BaseIndexTests(BaseExtensionTests): | ||
"""Tests for ExtensionIndex.""" | ||
|
||
def test_constructor(self, data): | ||
result = ExtensionIndex(data, name='test') | ||
assert result.name == 'test' | ||
self.assert_extension_array_equal(data, result._values) | ||
|
||
def test_series_constructor(self, data): | ||
result = pd.Series(range(len(data)), index=data) | ||
assert isinstance(result.index, ExtensionIndex) | ||
|
||
def test_asarray(self, data): | ||
idx = ExtensionIndex(data) | ||
tm.assert_numpy_array_equal(np.array(idx), np.array(data)) | ||
|
||
def test_repr(self, data): | ||
idx = ExtensionIndex(data, name='test') | ||
repr(idx) | ||
s = pd.Series(range(len(data)), index=data) | ||
repr(s) | ||
|
||
def test_indexing_scalar(self, data): | ||
s = pd.Series(range(len(data)), index=data) | ||
label = data[1] | ||
assert s[label] == 1 | ||
assert s.iloc[1] == 1 | ||
assert s.loc[label] == 1 | ||
|
||
def test_indexing_list(self, data): | ||
s = pd.Series(range(len(data)), index=data) | ||
labels = [data[1], data[3]] | ||
exp = pd.Series([1, 3], index=data[[1, 3]]) | ||
self.assert_series_equal(s[labels], exp) | ||
self.assert_series_equal(s.loc[labels], exp) | ||
self.assert_series_equal(s.iloc[[1, 3]], exp) | ||
|
||
def test_contains(self, data_missing, data_for_sorting, na_value): | ||
idx = ExtensionIndex(data_missing) | ||
assert data_missing[0] in idx | ||
assert data_missing[1] in idx | ||
assert na_value in idx | ||
assert '__random' not in idx | ||
idx = ExtensionIndex(data_for_sorting) | ||
assert na_value not in idx | ||
|
||
def test_na(self, data_missing): | ||
idx = ExtensionIndex(data_missing) | ||
result = idx.isna() | ||
expected = np.array([True, False], dtype=bool) | ||
tm.assert_numpy_array_equal(result, expected) | ||
result = idx.notna() | ||
tm.assert_numpy_array_equal(result, ~expected) | ||
assert idx.hasnans #is True | ||
|
||
def test_monotonic(self, data_for_sorting): | ||
data = data_for_sorting | ||
idx = ExtensionIndex(data) | ||
assert idx.is_monotonic_increasing is False | ||
assert idx.is_monotonic_decreasing is False | ||
|
||
idx = ExtensionIndex(data[[2, 0, 1]]) | ||
assert idx.is_monotonic_increasing is True | ||
assert idx.is_monotonic_decreasing is False | ||
|
||
idx = ExtensionIndex(data[[1, 0, 2]]) | ||
assert idx.is_monotonic_increasing is False | ||
assert idx.is_monotonic_decreasing is True | ||
|
||
def test_is_unique(self, data_for_sorting, data_for_grouping): | ||
idx = ExtensionIndex(data_for_sorting) | ||
assert idx.is_unique is True | ||
|
||
idx = ExtensionIndex(data_for_grouping) | ||
assert idx.is_unique is False | ||
|
||
def test_take(self, data): | ||
idx = ExtensionIndex(data) | ||
expected = ExtensionIndex(data.take([0, 2, 3])) | ||
result = idx.take([0, 2, 3]) | ||
tm.assert_index_equal(result, expected) | ||
|
||
def test_getitem(self, data): | ||
idx = ExtensionIndex(data) | ||
assert idx[0] == data[0] | ||
tm.assert_index_equal(idx[[0, 1]], ExtensionIndex(data[[0, 1]])) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ndarray -> extension array.