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

PERF: improve iloc list indexing #15504

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v0.20.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -905,7 +905,7 @@ Performance Improvements
- Improved performance of ``drop_duplicates()`` on ``bool`` columns (:issue:`12963`)
- Improve performance of ``pd.core.groupby.GroupBy.apply`` when the applied
function used the ``.name`` attribute of the group DataFrame (:issue:`15062`).

- Improved performance of ``iloc`` indexing with a list or array (:issue:`15504`).


.. _whatsnew_0200.bug_fixes:
Expand Down
24 changes: 14 additions & 10 deletions pandas/core/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1697,34 +1697,38 @@ def _get_slice_axis(self, slice_obj, axis=0):
else:
return self.obj.take(slice_obj, axis=axis, convert=False)

def _get_list_axis(self, key_list, axis=0):
def _get_list_axis(self, key, axis=0):
"""
Return Series values by list or array of integers

Parameters
----------
key_list : list-like positional indexer
key : list-like positional indexer
axis : int (can only be zero)

Returns
-------
Series object
"""

# validate list bounds
self._is_valid_list_like(key_list, axis)

# force an actual list
key_list = list(key_list)
return self.obj.take(key_list, axis=axis, convert=False)
try:
return self.obj.take(key, axis=axis, convert=False)
except IndexError:
# re-raise with different error message
raise IndexError("positional indexers are out-of-bounds")

def _getitem_axis(self, key, axis=0):

if isinstance(key, slice):
self._has_valid_type(key, axis)
return self._get_slice_axis(key, axis=axis)

elif is_bool_indexer(key):
if isinstance(key, list):
try:
key = np.asarray(key)
except TypeError: # pragma: no cover
pass

if is_bool_indexer(key):
self._has_valid_type(key, axis)
return self._getbool_axis(key, axis=axis)

Expand Down
7 changes: 4 additions & 3 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -2378,7 +2378,8 @@ def take(self, indices, axis=0, convert=True, is_copy=False, **kwargs):
--------
numpy.ndarray.take
"""
nv.validate_take(tuple(), kwargs)
if kwargs:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

assume this is going to go back after #15850 ?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can leave it in even then (for performance sensitive methods like take here). It is still 10x faster even after #15850 (although 10x is not that important anymore at those low numbers).

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ahh ok sure.

nv.validate_take(tuple(), kwargs)

# check/convert indicies here
if convert:
Expand All @@ -2387,8 +2388,8 @@ def take(self, indices, axis=0, convert=True, is_copy=False, **kwargs):
indices = _ensure_platform_int(indices)
new_index = self.index.take(indices)
new_values = self._values.take(indices)
return self._constructor(new_values,
index=new_index).__finalize__(self)
return (self._constructor(new_values, index=new_index, fastpath=True)
.__finalize__(self))

def isin(self, values):
"""
Expand Down
3 changes: 2 additions & 1 deletion pandas/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1668,7 +1668,8 @@ def _append_same_dtype(self, to_concat, name):
@Appender(_index_shared_docs['take'] % _index_doc_kwargs)
def take(self, indices, axis=0, allow_fill=True,
fill_value=None, **kwargs):
nv.validate_take(tuple(), kwargs)
if kwargs:
nv.validate_take(tuple(), kwargs)
indices = _ensure_platform_int(indices)
if self._can_hold_na:
taken = self._assert_take_fillable(self.values, indices,
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/test_generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -1870,7 +1870,7 @@ def test_take(self):
tm.makeObjectSeries()]:
out = s.take(indices)
expected = Series(data=s.values.take(indices),
index=s.index.take(indices))
index=s.index.take(indices), dtype=s.dtype)
tm.assert_series_equal(out, expected)
for df in [tm.makeTimeDataFrame()]:
out = df.take(indices)
Expand Down