Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 682e85f

Browse files
lesteveogrisel
authored andcommitted
Fix safe_indexing with read-only indices (#9507)
1 parent 9f91ec7 commit 682e85f

File tree

2 files changed

+11
-4
lines changed

2 files changed

+11
-4
lines changed

sklearn/utils/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,8 @@ def safe_indexing(X, indices):
142142
not supported.
143143
"""
144144
if hasattr(X, "iloc"):
145+
# Work-around for indexing with read-only indices in pandas
146+
indices = indices if indices.flags.writeable else indices.copy()
145147
# Pandas Dataframes and Series
146148
try:
147149
return X.iloc[indices]

sklearn/utils/tests/test_utils.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from itertools import chain
1+
from itertools import chain, product
22
import warnings
33

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

206-
assert_array_equal(np.array(X_df_ro_indexed), X_indexed)
206+
for this_df, this_inds in product([X_df, X_df_readonly],
207+
[inds, inds_readonly]):
208+
with warnings.catch_warnings(record=True):
209+
X_df_indexed = safe_indexing(this_df, this_inds)
210+
211+
assert_array_equal(np.array(X_df_indexed), X_indexed)
207212

208213

209214
def test_safe_indexing_mock_pandas():

0 commit comments

Comments
 (0)