Skip to content

Commit b2223f5

Browse files
author
MarcoGorelli
committed
Merge remote-tracking branch 'upstream/main' into pr/jorisvandenbossche/ruff
2 parents db0cf96 + 5718de1 commit b2223f5

File tree

7 files changed

+45
-9
lines changed

7 files changed

+45
-9
lines changed

pandas/core/generic.py

+12-5
Original file line numberDiff line numberDiff line change
@@ -1209,7 +1209,8 @@ class name
12091209
axes, kwargs = self._construct_axes_from_arguments(
12101210
(), kwargs, sentinel=lib.no_default
12111211
)
1212-
copy = kwargs.pop("copy", True)
1212+
copy: bool_t | None = kwargs.pop("copy", None)
1213+
12131214
inplace = kwargs.pop("inplace", False)
12141215
axis = kwargs.pop("axis", 0)
12151216
if axis is not None:
@@ -1229,7 +1230,9 @@ class name
12291230
is_list_like(mapper) and not is_dict_like(mapper)
12301231
)
12311232
if non_mapper:
1232-
return self._set_axis_name(mapper, axis=axis, inplace=inplace)
1233+
return self._set_axis_name(
1234+
mapper, axis=axis, inplace=inplace, copy=copy
1235+
)
12331236
else:
12341237
raise ValueError("Use `.rename` to alter labels with a mapper.")
12351238
else:
@@ -1248,13 +1251,15 @@ class name
12481251
f = common.get_rename_function(v)
12491252
curnames = self._get_axis(axis).names
12501253
newnames = [f(name) for name in curnames]
1251-
result._set_axis_name(newnames, axis=axis, inplace=True)
1254+
result._set_axis_name(newnames, axis=axis, inplace=True, copy=copy)
12521255
if not inplace:
12531256
return result
12541257
return None
12551258

12561259
@final
1257-
def _set_axis_name(self, name, axis: Axis = 0, inplace: bool_t = False):
1260+
def _set_axis_name(
1261+
self, name, axis: Axis = 0, inplace: bool_t = False, copy: bool_t | None = True
1262+
):
12581263
"""
12591264
Set the name(s) of the axis.
12601265
@@ -1267,6 +1272,8 @@ def _set_axis_name(self, name, axis: Axis = 0, inplace: bool_t = False):
12671272
and the value 1 or 'columns' specifies columns.
12681273
inplace : bool, default False
12691274
If `True`, do operation inplace and return None.
1275+
copy:
1276+
Whether to make a copy of the result.
12701277
12711278
Returns
12721279
-------
@@ -1308,7 +1315,7 @@ def _set_axis_name(self, name, axis: Axis = 0, inplace: bool_t = False):
13081315
idx = self._get_axis(axis).set_names(name)
13091316

13101317
inplace = validate_bool_kwarg(inplace, "inplace")
1311-
renamed = self if inplace else self.copy()
1318+
renamed = self if inplace else self.copy(deep=copy)
13121319
if axis == 0:
13131320
renamed.index = idx
13141321
else:

pandas/tests/copy_view/test_methods.py

+19
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
from pandas import (
55
DataFrame,
6+
Index,
67
MultiIndex,
78
Series,
89
)
@@ -456,3 +457,21 @@ def test_series_set_axis(using_copy_on_write):
456457
ser2.iloc[0] = 0
457458
assert not np.shares_memory(ser2, ser)
458459
tm.assert_series_equal(ser, ser_orig)
460+
461+
462+
@pytest.mark.parametrize("copy_kwargs", [{"copy": True}, {}])
463+
@pytest.mark.parametrize("kwargs", [{"mapper": "test"}, {"index": "test"}])
464+
def test_rename_axis(using_copy_on_write, kwargs, copy_kwargs):
465+
df = DataFrame({"a": [1, 2, 3, 4]}, index=Index([1, 2, 3, 4], name="a"))
466+
df_orig = df.copy()
467+
df2 = df.rename_axis(**kwargs, **copy_kwargs)
468+
469+
if using_copy_on_write and not copy_kwargs:
470+
assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
471+
else:
472+
assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
473+
474+
df2.iloc[0, 0] = 0
475+
if using_copy_on_write:
476+
assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
477+
tm.assert_frame_equal(df, df_orig)

pandas/tests/frame/methods/test_equals.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,8 @@ def test_equals(self):
3636
df1["start"] = date_range("2000-1-1", periods=10, freq="T")
3737
df1["end"] = date_range("2000-1-1", periods=10, freq="D")
3838
df1["diff"] = df1["end"] - df1["start"]
39-
df1["bool"] = np.arange(10) % 3 == 0
39+
# Explicitly cast to object, to avoid implicit cast when setting np.nan
40+
df1["bool"] = (np.arange(10) % 3 == 0).astype(object)
4041
df1.loc[::2] = np.nan
4142
df2 = df1.copy()
4243
assert df1["text"].equals(df2["text"])

pandas/tests/frame/test_query_eval.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -448,7 +448,8 @@ def test_date_index_query(self):
448448
def test_date_index_query_with_NaT(self):
449449
engine, parser = self.engine, self.parser
450450
n = 10
451-
df = DataFrame(np.random.randn(n, 3))
451+
# Cast to object to avoid implicit cast when setting entry to pd.NaT below
452+
df = DataFrame(np.random.randn(n, 3)).astype({0: object})
452453
df["dates1"] = date_range("1/1/2012", periods=n)
453454
df["dates3"] = date_range("1/1/2014", periods=n)
454455
df.iloc[0, 0] = pd.NaT
@@ -808,7 +809,8 @@ def test_date_index_query(self):
808809
def test_date_index_query_with_NaT(self):
809810
engine, parser = self.engine, self.parser
810811
n = 10
811-
df = DataFrame(np.random.randn(n, 3))
812+
# Cast to object to avoid implicit cast when setting entry to pd.NaT below
813+
df = DataFrame(np.random.randn(n, 3)).astype({0: object})
812814
df["dates1"] = date_range("1/1/2012", periods=n)
813815
df["dates3"] = date_range("1/1/2014", periods=n)
814816
df.iloc[0, 0] = pd.NaT

pandas/tests/frame/test_reductions.py

+4
Original file line numberDiff line numberDiff line change
@@ -449,10 +449,14 @@ def test_var_std(self, datetime_frame):
449449
def test_numeric_only_flag(self, meth):
450450
# GH 9201
451451
df1 = DataFrame(np.random.randn(5, 3), columns=["foo", "bar", "baz"])
452+
# Cast to object to avoid implicit cast when setting entry to "100" below
453+
df1 = df1.astype({"foo": object})
452454
# set one entry to a number in str format
453455
df1.loc[0, "foo"] = "100"
454456

455457
df2 = DataFrame(np.random.randn(5, 3), columns=["foo", "bar", "baz"])
458+
# Cast to object to avoid implicit cast when setting entry to "a" below
459+
df2 = df2.astype({"foo": object})
456460
# set one entry to a non-number str
457461
df2.loc[0, "foo"] = "a"
458462

pandas/tests/groupby/test_timegrouper.py

+2
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,8 @@ def test_groupby_with_timegrouper(self):
103103
"20130901", "20131205", freq="5D", name="Date", inclusive="left"
104104
),
105105
)
106+
# Cast to object to avoid implicit cast when setting entry to "CarlCarlCarl"
107+
expected = expected.astype({"Buyer": object})
106108
expected.iloc[0, 0] = "CarlCarlCarl"
107109
expected.iloc[6, 0] = "CarlCarl"
108110
expected.iloc[18, 0] = "Joe"

pandas/tests/series/methods/test_replace.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,8 @@ def test_replace_explicit_none(self):
1616
expected = pd.Series([0, 0, None], dtype=object)
1717
tm.assert_series_equal(result, expected)
1818

19-
df = pd.DataFrame(np.zeros((3, 3)))
19+
# Cast column 2 to object to avoid implicit cast when setting entry to ""
20+
df = pd.DataFrame(np.zeros((3, 3))).astype({2: object})
2021
df.iloc[2, 2] = ""
2122
result = df.replace("", None)
2223
expected = pd.DataFrame(

0 commit comments

Comments
 (0)