Skip to content

Commit

Permalink
Fix safe_indexing with read-only indices (scikit-learn#9507)
Browse files Browse the repository at this point in the history
  • Loading branch information
lesteve authored and paulha committed Aug 19, 2017
1 parent 22d05e6 commit b4e02e1
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
2 changes: 2 additions & 0 deletions sklearn/utils/__init__.py
Expand Up @@ -142,6 +142,8 @@ def safe_indexing(X, indices):
not supported.
"""
if hasattr(X, "iloc"):
# Work-around for indexing with read-only indices in pandas
indices = indices if indices.flags.writeable else indices.copy()
# Pandas Dataframes and Series
try:
return X.iloc[indices]
Expand Down
13 changes: 9 additions & 4 deletions sklearn/utils/tests/test_utils.py
@@ -1,4 +1,4 @@
from itertools import chain
from itertools import chain, product
import warnings

import numpy as np
Expand Down Expand Up @@ -200,10 +200,15 @@ def test_safe_indexing_pandas():
# this happens in joblib memmapping
X.setflags(write=False)
X_df_readonly = pd.DataFrame(X)
with warnings.catch_warnings(record=True):
X_df_ro_indexed = safe_indexing(X_df_readonly, inds)
inds_readonly = inds.copy()
inds_readonly.setflags(write=False)

assert_array_equal(np.array(X_df_ro_indexed), X_indexed)
for this_df, this_inds in product([X_df, X_df_readonly],
[inds, inds_readonly]):
with warnings.catch_warnings(record=True):
X_df_indexed = safe_indexing(this_df, this_inds)

assert_array_equal(np.array(X_df_indexed), X_indexed)


def test_safe_indexing_mock_pandas():
Expand Down

0 comments on commit b4e02e1

Please sign in to comment.