Skip to content

Commit 904f66e

Browse files
Revert "DEPR: inplace kwarg in set_index (pandas-dev#48115)"
This reverts commit 9de1f0b.
1 parent a9138a9 commit 904f66e

File tree

24 files changed

+52
-87
lines changed

24 files changed

+52
-87
lines changed

doc/source/user_guide/indexing.rst

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1723,12 +1723,13 @@ the given columns to a MultiIndex:
17231723
frame
17241724
17251725
Other options in ``set_index`` allow you not drop the index columns or to add
1726-
the index without creating a copy of the underlying data:
1726+
the index in-place (without creating a new object):
17271727

17281728
.. ipython:: python
17291729
17301730
data.set_index('c', drop=False)
1731-
data.set_index(['a', 'b'], copy=False)
1731+
data.set_index(['a', 'b'], inplace=True)
1732+
data
17321733
17331734
Reset the index
17341735
~~~~~~~~~~~~~~~

doc/source/whatsnew/v1.5.0.rst

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -932,7 +932,6 @@ Other Deprecations
932932
- Deprecated the ``inplace`` keyword in :meth:`DataFrame.set_axis` and :meth:`Series.set_axis`, use ``obj = obj.set_axis(..., copy=False)`` instead (:issue:`48130`)
933933
- Deprecated producing a single element when iterating over a :class:`DataFrameGroupBy` or a :class:`SeriesGroupBy` that has been grouped by a list of length 1; A tuple of length one will be returned instead (:issue:`42795`)
934934
- Fixed up warning message of deprecation of :meth:`MultiIndex.lesort_depth` as public method, as the message previously referred to :meth:`MultiIndex.is_lexsorted` instead (:issue:`38701`)
935-
- Deprecated the ``inplace`` keyword in :meth:`DataFrame.set_index`, use ``df = df.set_index(..., copy=False)`` instead (:issue:`48115`)
936935
- Deprecated the ``sort_columns`` argument in :meth:`DataFrame.plot` and :meth:`Series.plot` (:issue:`47563`).
937936
- Deprecated positional arguments for all but the first argument of :meth:`DataFrame.to_stata` and :func:`read_stata`, use keyword arguments instead (:issue:`48128`).
938937
- Deprecated the ``mangle_dupe_cols`` argument in :func:`read_csv`, :func:`read_fwf`, :func:`read_table` and :func:`read_excel`. The argument was never implemented, and a new argument where the renaming pattern can be specified will be added instead (:issue:`47718`)

pandas/core/frame.py

Lines changed: 3 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -5856,7 +5856,7 @@ def set_index(
58565856
*,
58575857
drop: bool = ...,
58585858
append: bool = ...,
5859-
inplace: Literal[False] | lib.NoDefault = ...,
5859+
inplace: Literal[False] = ...,
58605860
verify_integrity: bool = ...,
58615861
copy: bool | lib.NoDefault = ...,
58625862
) -> DataFrame:
@@ -5881,7 +5881,7 @@ def set_index(
58815881
keys,
58825882
drop: bool = True,
58835883
append: bool = False,
5884-
inplace: bool | lib.NoDefault = lib.no_default,
5884+
inplace: bool = False,
58855885
verify_integrity: bool = False,
58865886
copy: bool | lib.NoDefault = lib.no_default,
58875887
) -> DataFrame | None:
@@ -5906,9 +5906,6 @@ def set_index(
59065906
Whether to append columns to existing index.
59075907
inplace : bool, default False
59085908
Whether to modify the DataFrame rather than creating a new one.
5909-
5910-
.. deprecated:: 1.5.0
5911-
59125909
verify_integrity : bool, default False
59135910
Check the new index for duplicates. Otherwise defer the check until
59145911
necessary. Setting to False will improve the performance of this
@@ -5982,18 +5979,7 @@ def set_index(
59825979
3 9 7 2013 84
59835980
4 16 10 2014 31
59845981
"""
5985-
if inplace is not lib.no_default:
5986-
inplace = validate_bool_kwarg(inplace, "inplace")
5987-
warnings.warn(
5988-
"The 'inplace' keyword in DataFrame.set_index is deprecated "
5989-
"and will be removed in a future version. Use "
5990-
"`df = df.set_index(..., copy=False)` instead.",
5991-
FutureWarning,
5992-
stacklevel=find_stack_level(inspect.currentframe()),
5993-
)
5994-
else:
5995-
inplace = False
5996-
5982+
inplace = validate_bool_kwarg(inplace, "inplace")
59975983
if inplace:
59985984
if copy is not lib.no_default:
59995985
raise ValueError("Cannot specify copy when inplace=True")

pandas/core/reshape/merge.py

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -782,9 +782,9 @@ def get_result(self, copy: bool = True) -> DataFrame:
782782
if self.indicator:
783783
result = self._indicator_post_merge(result)
784784

785-
result = self._maybe_add_join_keys(result, left_indexer, right_indexer)
785+
self._maybe_add_join_keys(result, left_indexer, right_indexer)
786786

787-
result = self._maybe_restore_index_levels(result)
787+
self._maybe_restore_index_levels(result)
788788

789789
self._maybe_drop_cross_column(result, self._cross)
790790

@@ -851,7 +851,7 @@ def _indicator_post_merge(self, result: DataFrame) -> DataFrame:
851851
result = result.drop(labels=["_left_indicator", "_right_indicator"], axis=1)
852852
return result
853853

854-
def _maybe_restore_index_levels(self, result: DataFrame) -> DataFrame:
854+
def _maybe_restore_index_levels(self, result: DataFrame) -> None:
855855
"""
856856
Restore index levels specified as `on` parameters
857857
@@ -869,7 +869,7 @@ def _maybe_restore_index_levels(self, result: DataFrame) -> DataFrame:
869869
870870
Returns
871871
-------
872-
DataFrame
872+
None
873873
"""
874874
names_to_restore = []
875875
for name, left_key, right_key in zip(
@@ -893,15 +893,14 @@ def _maybe_restore_index_levels(self, result: DataFrame) -> DataFrame:
893893
names_to_restore.append(name)
894894

895895
if names_to_restore:
896-
result = result.set_index(names_to_restore, copy=False)
897-
return result
896+
result.set_index(names_to_restore, inplace=True)
898897

899898
def _maybe_add_join_keys(
900899
self,
901900
result: DataFrame,
902901
left_indexer: np.ndarray | None,
903902
right_indexer: np.ndarray | None,
904-
) -> DataFrame:
903+
) -> None:
905904

906905
left_has_missing = None
907906
right_has_missing = None
@@ -992,12 +991,11 @@ def _maybe_add_join_keys(
992991
for level_name in result.index.names
993992
]
994993

995-
result = result.set_index(idx_list, copy=False)
994+
result.set_index(idx_list, inplace=True)
996995
else:
997996
result.index = Index(key_col, name=name)
998997
else:
999998
result.insert(i, name or f"key_{i}", key_col)
1000-
return result
1001999

10021000
def _get_join_indexers(self) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]:
10031001
"""return the join indexers"""
@@ -1767,8 +1765,7 @@ def get_result(self, copy: bool = True) -> DataFrame:
17671765
result = self._reindex_and_concat(
17681766
join_index, left_join_indexer, right_join_indexer, copy=copy
17691767
)
1770-
1771-
result = self._maybe_add_join_keys(result, left_indexer, right_indexer)
1768+
self._maybe_add_join_keys(result, left_indexer, right_indexer)
17721769

17731770
return result
17741771

pandas/io/parsers/arrow_parser_wrapper.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ def _finalize_output(self, frame: DataFrame) -> DataFrame:
117117
# String case
118118
if item not in frame.columns:
119119
raise ValueError(f"Index {item} invalid")
120-
frame = frame.set_index(self.index_col, drop=True, copy=False)
120+
frame.set_index(self.index_col, drop=True, inplace=True)
121121
# Clear names if headerless and no name given
122122
if self.header is None and not multi_index_named:
123123
frame.index.names = [None] * len(frame.index.names)

pandas/io/pytables.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4667,7 +4667,7 @@ def read(
46674667
columns.insert(0, n)
46684668
s = super().read(where=where, columns=columns, start=start, stop=stop)
46694669
if is_multi_index:
4670-
s = s.set_index(self.levels, copy=False)
4670+
s.set_index(self.levels, inplace=True)
46714671

46724672
s = s.iloc[:, 0]
46734673

pandas/io/sql.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,7 @@ def _wrap_result(
152152
frame = _parse_date_columns(frame, parse_dates)
153153

154154
if index_col is not None:
155-
frame = frame.set_index(index_col, copy=False)
155+
frame.set_index(index_col, inplace=True)
156156

157157
return frame
158158

@@ -980,7 +980,7 @@ def _query_iterator(
980980
self._harmonize_columns(parse_dates=parse_dates)
981981

982982
if self.index is not None:
983-
self.frame = self.frame.set_index(self.index, copy=False)
983+
self.frame.set_index(self.index, inplace=True)
984984

985985
yield self.frame
986986

@@ -1021,7 +1021,7 @@ def read(
10211021
self._harmonize_columns(parse_dates=parse_dates)
10221022

10231023
if self.index is not None:
1024-
self.frame = self.frame.set_index(self.index, copy=False)
1024+
self.frame.set_index(self.index, inplace=True)
10251025

10261026
return self.frame
10271027

pandas/tests/frame/methods/test_combine_first.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -394,12 +394,12 @@ def test_combine_first_string_dtype_only_na(self, nullable_string_dtype):
394394
PerformanceWarning,
395395
pa_version_under7p0 and nullable_string_dtype == "string[pyarrow]",
396396
):
397-
df = df.set_index(["a", "b"], copy=False)
397+
df.set_index(["a", "b"], inplace=True)
398398
with tm.maybe_produces_warning(
399399
PerformanceWarning,
400400
pa_version_under7p0 and nullable_string_dtype == "string[pyarrow]",
401401
):
402-
df2 = df2.set_index(["a", "b"], copy=False)
402+
df2.set_index(["a", "b"], inplace=True)
403403
result = df.combine_first(df2)
404404
with tm.maybe_produces_warning(
405405
PerformanceWarning,

pandas/tests/frame/methods/test_set_index.py

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -40,11 +40,9 @@ def test_set_index_copy(self):
4040

4141
msg = "Cannot specify copy when inplace=True"
4242
with pytest.raises(ValueError, match=msg):
43-
with tm.assert_produces_warning(FutureWarning, match="The 'inplace'"):
44-
df.set_index("A", inplace=True, copy=True)
43+
df.set_index("A", inplace=True, copy=True)
4544
with pytest.raises(ValueError, match=msg):
46-
with tm.assert_produces_warning(FutureWarning, match="The 'inplace'"):
47-
df.set_index("A", inplace=True, copy=False)
45+
df.set_index("A", inplace=True, copy=False)
4846

4947
def test_set_index_multiindex(self):
5048
# segfault in GH#3308
@@ -199,10 +197,7 @@ def test_set_index_drop_inplace(self, frame_of_index_cols, drop, inplace, keys):
199197

200198
if inplace:
201199
result = df.copy()
202-
with tm.assert_produces_warning(
203-
FutureWarning, match="The 'inplace' keyword"
204-
):
205-
return_value = result.set_index(keys, drop=drop, inplace=True)
200+
return_value = result.set_index(keys, drop=drop, inplace=True)
206201
assert return_value is None
207202
else:
208203
result = df.set_index(keys, drop=drop)

pandas/tests/frame/test_api.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -244,8 +244,7 @@ def _check_f(base, f):
244244

245245
# set_index
246246
f = lambda x: x.set_index("a", inplace=True)
247-
with tm.assert_produces_warning(FutureWarning, match="The 'inplace' keyword"):
248-
_check_f(data.copy(), f)
247+
_check_f(data.copy(), f)
249248

250249
# reset_index
251250
f = lambda x: x.reset_index(inplace=True)

pandas/tests/frame/test_query_eval.py

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -436,8 +436,7 @@ def test_date_index_query(self):
436436
df = DataFrame(np.random.randn(n, 3))
437437
df["dates1"] = date_range("1/1/2012", periods=n)
438438
df["dates3"] = date_range("1/1/2014", periods=n)
439-
with tm.assert_produces_warning(FutureWarning, match="The 'inplace' keyword"):
440-
return_value = df.set_index("dates1", inplace=True, drop=True)
439+
return_value = df.set_index("dates1", inplace=True, drop=True)
441440
assert return_value is None
442441
res = df.query("index < 20130101 < dates3", engine=engine, parser=parser)
443442
expec = df[(df.index < "20130101") & ("20130101" < df.dates3)]
@@ -450,8 +449,7 @@ def test_date_index_query_with_NaT(self):
450449
df["dates1"] = date_range("1/1/2012", periods=n)
451450
df["dates3"] = date_range("1/1/2014", periods=n)
452451
df.iloc[0, 0] = pd.NaT
453-
with tm.assert_produces_warning(FutureWarning, match="The 'inplace' keyword"):
454-
return_value = df.set_index("dates1", inplace=True, drop=True)
452+
return_value = df.set_index("dates1", inplace=True, drop=True)
455453
assert return_value is None
456454
res = df.query("index < 20130101 < dates3", engine=engine, parser=parser)
457455
expec = df[(df.index < "20130101") & ("20130101" < df.dates3)]
@@ -465,8 +463,7 @@ def test_date_index_query_with_NaT_duplicates(self):
465463
d["dates3"] = date_range("1/1/2014", periods=n)
466464
df = DataFrame(d)
467465
df.loc[np.random.rand(n) > 0.5, "dates1"] = pd.NaT
468-
with tm.assert_produces_warning(FutureWarning, match="The 'inplace' keyword"):
469-
return_value = df.set_index("dates1", inplace=True, drop=True)
466+
return_value = df.set_index("dates1", inplace=True, drop=True)
470467
assert return_value is None
471468
res = df.query("dates1 < 20130101 < dates3", engine=engine, parser=parser)
472469
expec = df[(df.index.to_series() < "20130101") & ("20130101" < df.dates3)]
@@ -797,8 +794,7 @@ def test_date_index_query(self):
797794
df = DataFrame(np.random.randn(n, 3))
798795
df["dates1"] = date_range("1/1/2012", periods=n)
799796
df["dates3"] = date_range("1/1/2014", periods=n)
800-
with tm.assert_produces_warning(FutureWarning, match="The 'inplace' keyword"):
801-
return_value = df.set_index("dates1", inplace=True, drop=True)
797+
return_value = df.set_index("dates1", inplace=True, drop=True)
802798
assert return_value is None
803799
res = df.query(
804800
"(index < 20130101) & (20130101 < dates3)", engine=engine, parser=parser
@@ -813,8 +809,7 @@ def test_date_index_query_with_NaT(self):
813809
df["dates1"] = date_range("1/1/2012", periods=n)
814810
df["dates3"] = date_range("1/1/2014", periods=n)
815811
df.iloc[0, 0] = pd.NaT
816-
with tm.assert_produces_warning(FutureWarning, match="The 'inplace' keyword"):
817-
return_value = df.set_index("dates1", inplace=True, drop=True)
812+
return_value = df.set_index("dates1", inplace=True, drop=True)
818813
assert return_value is None
819814
res = df.query(
820815
"(index < 20130101) & (20130101 < dates3)", engine=engine, parser=parser
@@ -829,8 +824,7 @@ def test_date_index_query_with_NaT_duplicates(self):
829824
df["dates1"] = date_range("1/1/2012", periods=n)
830825
df["dates3"] = date_range("1/1/2014", periods=n)
831826
df.loc[np.random.rand(n) > 0.5, "dates1"] = pd.NaT
832-
with tm.assert_produces_warning(FutureWarning, match="The 'inplace' keyword"):
833-
return_value = df.set_index("dates1", inplace=True, drop=True)
827+
return_value = df.set_index("dates1", inplace=True, drop=True)
834828
assert return_value is None
835829
msg = r"'BoolOp' nodes are not implemented"
836830
with pytest.raises(NotImplementedError, match=msg):

pandas/tests/groupby/test_apply.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -678,7 +678,7 @@ def test_apply_groupby_datetimeindex():
678678
result = df.groupby("Name").sum()
679679

680680
expected = DataFrame({"Name": ["A", "B", "C"], "Value": [10, 50, 90]})
681-
expected = expected.set_index("Name", copy=False)
681+
expected.set_index("Name", inplace=True)
682682

683683
tm.assert_frame_equal(result, expected)
684684

pandas/tests/groupby/test_function.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ def test_builtins_apply(keys, f):
9898

9999
if f != sum:
100100
expected = gb.agg(fname).reset_index()
101-
expected = expected.set_index(keys, copy=False, drop=False)
101+
expected.set_index(keys, inplace=True, drop=False)
102102
tm.assert_frame_equal(result, expected, check_dtype=False)
103103

104104
tm.assert_series_equal(getattr(result, fname)(), getattr(df, fname)())
@@ -454,7 +454,7 @@ def test_groupby_non_arithmetic_agg_types(dtype, method, data):
454454
df_out = DataFrame(exp)
455455

456456
df_out["b"] = df_out.b.astype(out_type)
457-
df_out = df_out.set_index("a", copy=False)
457+
df_out.set_index("a", inplace=True)
458458

459459
grpd = df.groupby("a")
460460
t = getattr(grpd, method)(*data["args"])

pandas/tests/indexes/multi/test_reshape.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ def test_insert(idx):
3535
idx.insert(0, ("foo2",))
3636

3737
left = pd.DataFrame([["a", "b", 0], ["b", "d", 1]], columns=["1st", "2nd", "3rd"])
38-
left = left.set_index(["1st", "2nd"], copy=False)
38+
left.set_index(["1st", "2nd"], inplace=True)
3939
ts = left["3rd"].copy(deep=True)
4040

4141
left.loc[("b", "x"), "3rd"] = 2
@@ -65,7 +65,7 @@ def test_insert(idx):
6565
],
6666
columns=["1st", "2nd", "3rd"],
6767
)
68-
right = right.set_index(["1st", "2nd"], copy=False)
68+
right.set_index(["1st", "2nd"], inplace=True)
6969
# FIXME data types changes to float because
7070
# of intermediate nan insertion;
7171
tm.assert_frame_equal(left, right, check_dtype=False)

pandas/tests/indexing/multiindex/test_indexing_slow.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -60,18 +60,15 @@ def validate(mi, df, key):
6060
assert key[: i + 1] in mi.index
6161
right = df[mask].copy()
6262

63-
msg = "The 'inplace' keyword in DataFrame.set_index is deprecated"
6463
if i + 1 != len(key): # partial key
6564
return_value = right.drop(cols[: i + 1], axis=1, inplace=True)
6665
assert return_value is None
67-
with tm.assert_produces_warning(FutureWarning, match=msg):
68-
return_value = right.set_index(cols[i + 1 : -1], inplace=True)
66+
return_value = right.set_index(cols[i + 1 : -1], inplace=True)
6967
assert return_value is None
7068
tm.assert_frame_equal(mi.loc[key[: i + 1]], right)
7169

7270
else: # full key
73-
with tm.assert_produces_warning(FutureWarning, match=msg):
74-
return_value = right.set_index(cols[:-1], inplace=True)
71+
return_value = right.set_index(cols[:-1], inplace=True)
7572
assert return_value is None
7673
if len(right) == 1: # single hit
7774
right = Series(

pandas/tests/indexing/multiindex/test_multiindex.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ def test_multiindex_complex(self):
131131
"z": non_complex_data,
132132
}
133133
)
134-
result = result.set_index(["x", "y"], copy=False)
134+
result.set_index(["x", "y"], inplace=True)
135135
expected = DataFrame(
136136
{"z": non_complex_data},
137137
index=MultiIndex.from_arrays(

pandas/tests/io/pytables/test_append.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ def test_append_series(setup_path):
137137
mi["B"] = np.arange(len(mi))
138138
mi["C"] = "foo"
139139
mi.loc[3:5, "C"] = "bar"
140-
mi = mi.set_index(["C", "B"], copy=False)
140+
mi.set_index(["C", "B"], inplace=True)
141141
s = mi.stack()
142142
s.index = s.index.droplevel(2)
143143
store.append("mi", s)
@@ -326,7 +326,7 @@ def test_append_with_different_block_ordering(setup_path):
326326
a = df.pop("A")
327327
df["A"] = a
328328

329-
df = df.set_index("index", copy=False)
329+
df.set_index("index", inplace=True)
330330

331331
store.append("df", df)
332332

0 commit comments

Comments
 (0)