Skip to content

Commit 79fb2de

Browse files
authored
TYP: rename (pandas-dev#46428)
1 parent 1f2d54a commit 79fb2de

File tree

6 files changed

+105
-126
lines changed

6 files changed

+105
-126
lines changed

pandas/_typing.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,7 @@
141141
]
142142

143143
# For functions like rename that convert one label to another
144-
Renamer = Union[Mapping[Hashable, Any], Callable[[Hashable], Hashable]]
144+
Renamer = Union[Mapping[Any, Hashable], Callable[[Any], Hashable]]
145145

146146
# to maintain type information across generic functions and parametrization
147147
T = TypeVar("T")

pandas/core/frame.py

+46-1
Original file line numberDiff line numberDiff line change
@@ -5030,6 +5030,51 @@ def drop( # type: ignore[override]
50305030
errors=errors,
50315031
)
50325032

5033+
@overload
5034+
def rename(
5035+
self,
5036+
mapper: Renamer | None = ...,
5037+
*,
5038+
index: Renamer | None = ...,
5039+
columns: Renamer | None = ...,
5040+
axis: Axis | None = ...,
5041+
copy: bool = ...,
5042+
inplace: Literal[True],
5043+
level: Level | None = ...,
5044+
errors: IgnoreRaise = ...,
5045+
) -> None:
5046+
...
5047+
5048+
@overload
5049+
def rename(
5050+
self,
5051+
mapper: Renamer | None = ...,
5052+
*,
5053+
index: Renamer | None = ...,
5054+
columns: Renamer | None = ...,
5055+
axis: Axis | None = ...,
5056+
copy: bool = ...,
5057+
inplace: Literal[False] = ...,
5058+
level: Level | None = ...,
5059+
errors: IgnoreRaise = ...,
5060+
) -> DataFrame:
5061+
...
5062+
5063+
@overload
5064+
def rename(
5065+
self,
5066+
mapper: Renamer | None = ...,
5067+
*,
5068+
index: Renamer | None = ...,
5069+
columns: Renamer | None = ...,
5070+
axis: Axis | None = ...,
5071+
copy: bool = ...,
5072+
inplace: bool = ...,
5073+
level: Level | None = ...,
5074+
errors: IgnoreRaise = ...,
5075+
) -> DataFrame | None:
5076+
...
5077+
50335078
def rename(
50345079
self,
50355080
mapper: Renamer | None = None,
@@ -5040,7 +5085,7 @@ def rename(
50405085
copy: bool = True,
50415086
inplace: bool = False,
50425087
level: Level | None = None,
5043-
errors: str = "ignore",
5088+
errors: IgnoreRaise = "ignore",
50445089
) -> DataFrame | None:
50455090
"""
50465091
Alter axes labels.

pandas/core/generic.py

+1-110
Original file line numberDiff line numberDiff line change
@@ -984,117 +984,8 @@ def _rename(
984984
level: Level | None = None,
985985
errors: str = "ignore",
986986
) -> NDFrameT | None:
987-
"""
988-
Alter axes input function or functions. Function / dict values must be
989-
unique (1-to-1). Labels not contained in a dict / Series will be left
990-
as-is. Extra labels listed don't throw an error. Alternatively, change
991-
``Series.name`` with a scalar value (Series only).
992-
993-
Parameters
994-
----------
995-
%(axes)s : scalar, list-like, dict-like or function, optional
996-
Scalar or list-like will alter the ``Series.name`` attribute,
997-
and raise on DataFrame.
998-
dict-like or functions are transformations to apply to
999-
that axis' values
1000-
copy : bool, default True
1001-
Also copy underlying data.
1002-
inplace : bool, default False
1003-
Whether to return a new {klass}. If True then value of copy is
1004-
ignored.
1005-
level : int or level name, default None
1006-
In case of a MultiIndex, only rename labels in the specified
1007-
level.
1008-
errors : {'ignore', 'raise'}, default 'ignore'
1009-
If 'raise', raise a `KeyError` when a dict-like `mapper`, `index`,
1010-
or `columns` contains labels that are not present in the Index
1011-
being transformed.
1012-
If 'ignore', existing keys will be renamed and extra keys will be
1013-
ignored.
1014-
1015-
Returns
1016-
-------
1017-
renamed : {klass} (new object)
1018-
1019-
Raises
1020-
------
1021-
KeyError
1022-
If any of the labels is not found in the selected axis and
1023-
"errors='raise'".
987+
# called by Series.rename and DataFrame.rename
1024988

1025-
See Also
1026-
--------
1027-
NDFrame.rename_axis
1028-
1029-
Examples
1030-
--------
1031-
>>> s = pd.Series([1, 2, 3])
1032-
>>> s
1033-
0 1
1034-
1 2
1035-
2 3
1036-
dtype: int64
1037-
>>> s.rename("my_name") # scalar, changes Series.name
1038-
0 1
1039-
1 2
1040-
2 3
1041-
Name: my_name, dtype: int64
1042-
>>> s.rename(lambda x: x ** 2) # function, changes labels
1043-
0 1
1044-
1 2
1045-
4 3
1046-
dtype: int64
1047-
>>> s.rename({1: 3, 2: 5}) # mapping, changes labels
1048-
0 1
1049-
3 2
1050-
5 3
1051-
dtype: int64
1052-
1053-
Since ``DataFrame`` doesn't have a ``.name`` attribute,
1054-
only mapping-type arguments are allowed.
1055-
1056-
>>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
1057-
>>> df.rename(2)
1058-
Traceback (most recent call last):
1059-
...
1060-
TypeError: 'int' object is not callable
1061-
1062-
``DataFrame.rename`` supports two calling conventions
1063-
1064-
* ``(index=index_mapper, columns=columns_mapper, ...)``
1065-
* ``(mapper, axis={'index', 'columns'}, ...)``
1066-
1067-
We *highly* recommend using keyword arguments to clarify your
1068-
intent.
1069-
1070-
>>> df.rename(index=str, columns={"A": "a", "B": "c"})
1071-
a c
1072-
0 1 4
1073-
1 2 5
1074-
2 3 6
1075-
1076-
>>> df.rename(index=str, columns={"A": "a", "C": "c"})
1077-
a B
1078-
0 1 4
1079-
1 2 5
1080-
2 3 6
1081-
1082-
Using axis-style parameters
1083-
1084-
>>> df.rename(str.lower, axis='columns')
1085-
a b
1086-
0 1 4
1087-
1 2 5
1088-
2 3 6
1089-
1090-
>>> df.rename({1: 2, 2: 4}, axis='index')
1091-
A B
1092-
0 1 4
1093-
2 2 5
1094-
4 3 6
1095-
1096-
See the :ref:`user guide <basics.rename>` for more.
1097-
"""
1098989
if mapper is None and index is None and columns is None:
1099990
raise TypeError("must pass an index to rename")
1100991

pandas/core/groupby/groupby.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -2204,8 +2204,7 @@ def size(self) -> DataFrame | Series:
22042204
result = self._obj_1d_constructor(result)
22052205

22062206
if not self.as_index:
2207-
# Item "None" of "Optional[Series]" has no attribute "reset_index"
2208-
result = result.rename("size").reset_index() # type: ignore[union-attr]
2207+
result = result.rename("size").reset_index()
22092208

22102209
return self._reindex_output(result, fill_value=0)
22112210

pandas/core/series.py

+55-7
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242
IndexKeyFunc,
4343
Level,
4444
NaPosition,
45+
Renamer,
4546
SingleManager,
4647
SortKind,
4748
StorageOptions,
@@ -4617,15 +4618,54 @@ def align(
46174618
broadcast_axis=broadcast_axis,
46184619
)
46194620

4621+
@overload
46204622
def rename(
46214623
self,
4622-
index=None,
4624+
index: Renamer | Hashable | None = ...,
46234625
*,
4624-
axis=None,
4625-
copy=True,
4626-
inplace=False,
4627-
level=None,
4628-
errors="ignore",
4626+
axis: Axis | None = ...,
4627+
copy: bool = ...,
4628+
inplace: Literal[True],
4629+
level: Level | None = ...,
4630+
errors: IgnoreRaise = ...,
4631+
) -> None:
4632+
...
4633+
4634+
@overload
4635+
def rename(
4636+
self,
4637+
index: Renamer | Hashable | None = ...,
4638+
*,
4639+
axis: Axis | None = ...,
4640+
copy: bool = ...,
4641+
inplace: Literal[False] = ...,
4642+
level: Level | None = ...,
4643+
errors: IgnoreRaise = ...,
4644+
) -> Series:
4645+
...
4646+
4647+
@overload
4648+
def rename(
4649+
self,
4650+
index: Renamer | Hashable | None = ...,
4651+
*,
4652+
axis: Axis | None = ...,
4653+
copy: bool = ...,
4654+
inplace: bool = ...,
4655+
level: Level | None = ...,
4656+
errors: IgnoreRaise = ...,
4657+
) -> Series | None:
4658+
...
4659+
4660+
def rename(
4661+
self,
4662+
index: Renamer | Hashable | None = None,
4663+
*,
4664+
axis: Axis | None = None,
4665+
copy: bool = True,
4666+
inplace: bool = False,
4667+
level: Level | None = None,
4668+
errors: IgnoreRaise = "ignore",
46294669
) -> Series | None:
46304670
"""
46314671
Alter Series index labels or name.
@@ -4691,8 +4731,16 @@ def rename(
46914731
axis = self._get_axis_number(axis)
46924732

46934733
if callable(index) or is_dict_like(index):
4734+
# error: Argument 1 to "_rename" of "NDFrame" has incompatible
4735+
# type "Union[Union[Mapping[Any, Hashable], Callable[[Any],
4736+
# Hashable]], Hashable, None]"; expected "Union[Mapping[Any,
4737+
# Hashable], Callable[[Any], Hashable], None]"
46944738
return super()._rename(
4695-
index, copy=copy, inplace=inplace, level=level, errors=errors
4739+
index, # type: ignore[arg-type]
4740+
copy=copy,
4741+
inplace=inplace,
4742+
level=level,
4743+
errors=errors,
46964744
)
46974745
else:
46984746
return self._set_name(index, inplace=inplace)

pandas/io/json/_normalize.py

+1-5
Original file line numberDiff line numberDiff line change
@@ -520,11 +520,7 @@ def _recursive_extract(data, path, seen_meta, level=0):
520520
result = DataFrame(records)
521521

522522
if record_prefix is not None:
523-
# Incompatible types in assignment (expression has type "Optional[DataFrame]",
524-
# variable has type "DataFrame")
525-
result = result.rename( # type: ignore[assignment]
526-
columns=lambda x: f"{record_prefix}{x}"
527-
)
523+
result = result.rename(columns=lambda x: f"{record_prefix}{x}")
528524

529525
# Data types, a problem
530526
for k, v in meta_vals.items():

0 commit comments

Comments
 (0)