Skip to content

Commit f09c6df

Browse files
committed
Worked around frame edges
1 parent 6c898e6 commit f09c6df

File tree

4 files changed

+78
-40
lines changed

4 files changed

+78
-40
lines changed

pandas/_typing.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
FrameOrSeries = TypeVar("FrameOrSeries", bound="NDFrame")
2525
Scalar = Union[str, int, float, bool]
2626
Axis = Union[str, int]
27+
Level = Union[str, int]
2728
Ordered = Optional[bool]
2829

2930
# use Collection after we drop support for py35

pandas/core/frame.py

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,12 @@
1515
import sys
1616
from textwrap import dedent
1717
from typing import (
18+
Callable,
1819
FrozenSet,
1920
Hashable,
2021
Iterable,
2122
List,
23+
Mapping,
2224
Optional,
2325
Sequence,
2426
Set,
@@ -93,7 +95,7 @@
9395
)
9496
from pandas.core.dtypes.missing import isna, notna
9597

96-
from pandas._typing import Axes, Dtype, FilePathOrBuffer
98+
from pandas._typing import Axis, Axes, Dtype, FilePathOrBuffer, Level
9799
from pandas.core import algorithms, common as com, nanops, ops
98100
from pandas.core.accessor import CachedAccessor
99101
from pandas.core.arrays import Categorical, ExtensionArray
@@ -4031,7 +4033,24 @@ def drop(
40314033
"mapper",
40324034
[("copy", True), ("inplace", False), ("level", None), ("errors", "ignore")],
40334035
)
4034-
def rename(self, *args, **kwargs):
4036+
def rename(
4037+
self,
4038+
mapper: Optional[
4039+
Union[Mapping[Hashable, Hashable], Callable[[Hashable], Hashable]]
4040+
] = None,
4041+
index: Optional[
4042+
Union[Mapping[Hashable, Hashable], Callable[[Hashable], Hashable]]
4043+
] = None,
4044+
columns: Optional[
4045+
Union[Mapping[Hashable, Hashable], Callable[[Hashable], Hashable]]
4046+
] = None,
4047+
axis: Optional[Axis] = None,
4048+
copy: bool = True,
4049+
inplace: bool = False,
4050+
level: Optional[Level] = None,
4051+
errors: str = "ignore",
4052+
) -> "DataFrame":
4053+
40354054
"""
40364055
Alter axes labels.
40374056
@@ -4140,12 +4159,8 @@ def rename(self, *args, **kwargs):
41404159
2 2 5
41414160
4 3 6
41424161
"""
4143-
axes = validate_axis_style_args(self, args, kwargs, "mapper", "rename")
4144-
kwargs.update(axes)
4145-
# Pop these, since the values are in `kwargs` under different names
4146-
kwargs.pop("axis", None)
4147-
kwargs.pop("mapper", None)
4148-
return super().rename(**kwargs)
4162+
return super().rename(mapper=mapper, index=index, columns=columns, axis=axis, copy=copy,
4163+
inplace=inplace, level=level, errors=errors)
41494164

41504165
@Substitution(**_shared_doc_kwargs)
41514166
@Appender(NDFrame.fillna.__doc__)

pandas/core/generic.py

Lines changed: 43 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
FrozenSet,
1515
Hashable,
1616
List,
17+
Mapping,
1718
Optional,
1819
Sequence,
1920
Set,
@@ -65,7 +66,7 @@
6566
from pandas.core.dtypes.missing import isna, notna
6667

6768
import pandas as pd
68-
from pandas._typing import Dtype, FilePathOrBuffer, Scalar
69+
from pandas._typing import Axis, Dtype, FilePathOrBuffer, Level, Scalar
6970
from pandas.core import missing, nanops
7071
import pandas.core.algorithms as algos
7172
from pandas.core.base import PandasObject, SelectionMixin
@@ -1013,7 +1014,23 @@ def swaplevel(self, i=-2, j=-1, axis=0):
10131014
# ----------------------------------------------------------------------
10141015
# Rename
10151016

1016-
def rename(self, *args, **kwargs):
1017+
def rename(
1018+
self,
1019+
mapper: Optional[
1020+
Union[Mapping[Hashable, Hashable], Callable[[Hashable], Hashable]]
1021+
] = None,
1022+
index: Optional[
1023+
Union[Mapping[Hashable, Hashable], Callable[[Hashable], Hashable]]
1024+
] = None,
1025+
columns: Optional[
1026+
Union[Mapping[Hashable, Hashable], Callable[[Hashable], Hashable]]
1027+
] = None,
1028+
axis: Optional[Axis] = None,
1029+
copy: bool = True,
1030+
inplace: bool = False,
1031+
level: Optional[Level] = None,
1032+
errors: str = "ignore",
1033+
):
10171034
"""
10181035
Alter axes input function or functions. Function / dict values must be
10191036
unique (1-to-1). Labels not contained in a dict / Series will be left
@@ -1126,44 +1143,40 @@ def rename(self, *args, **kwargs):
11261143
11271144
See the :ref:`user guide <basics.rename>` for more.
11281145
"""
1129-
axes, kwargs = self._construct_axes_from_arguments(args, kwargs)
1130-
copy = kwargs.pop("copy", True)
1131-
inplace = kwargs.pop("inplace", False)
1132-
level = kwargs.pop("level", None)
1133-
axis = kwargs.pop("axis", None)
1134-
errors = kwargs.pop("errors", "ignore")
1135-
if axis is not None:
1136-
# Validate the axis
1137-
self._get_axis_number(axis)
1138-
1139-
if kwargs:
1140-
raise TypeError(
1141-
"rename() got an unexpected keyword "
1142-
'argument "{0}"'.format(list(kwargs.keys())[0])
1143-
)
1144-
1145-
if com.count_not_none(*axes.values()) == 0:
1146+
if not (mapper or index or columns):
11461147
raise TypeError("must pass an index to rename")
11471148

1148-
self._consolidate_inplace()
1149+
if (index or columns):
1150+
if axis is not None:
1151+
raise TypeError("Cannot specify both 'axis' and any of 'index' or 'columns'")
1152+
elif mapper:
1153+
raise TypeError("Cannot specify both 'mapper' and any of 'index' or 'columns'")
1154+
else:
1155+
# use the mapper argument
1156+
if axis in {1, "columns"}:
1157+
columns = mapper
1158+
else:
1159+
index = mapper
1160+
11491161
result = self if inplace else self.copy(deep=copy)
11501162

1151-
# start in the axis order to eliminate too many copies
1152-
for axis in range(self._AXIS_LEN):
1153-
v = axes.get(self._AXIS_NAMES[axis])
1154-
if v is None:
1163+
for axis_no, replacements in enumerate((index, columns)):
1164+
if replacements is None:
11551165
continue
1156-
f = com.get_rename_function(v)
1157-
baxis = self._get_block_manager_axis(axis)
1166+
1167+
axis = self._get_axis(axis_no)
1168+
baxis = self._get_block_manager_axis(axis_no)
1169+
f = com.get_rename_function(replacements)
1170+
11581171
if level is not None:
1159-
level = self.axes[axis]._get_level_number(level)
1172+
level = axis._get_level_number(level)
11601173

11611174
# GH 13473
1162-
if not callable(v):
1163-
indexer = self.axes[axis].get_indexer_for(v)
1175+
if not callable(replacements):
1176+
indexer = axis.get_indexer_for(replacements)
11641177
if errors == "raise" and len(indexer[indexer == -1]):
11651178
missing_labels = [
1166-
label for index, label in enumerate(v) if indexer[index] == -1
1179+
label for index, label in enumerate(replacements) if indexer[index] == -1
11671180
]
11681181
raise KeyError("{} not found in axis".format(missing_labels))
11691182

pandas/core/series.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from io import StringIO
66
from shutil import get_terminal_size
77
from textwrap import dedent
8-
from typing import Any, Callable
8+
from typing import Any, Callable, Hashable, Mapping, Optional, Union
99
import warnings
1010

1111
import numpy as np
@@ -78,6 +78,7 @@
7878
from pandas.core.strings import StringMethods
7979
from pandas.core.tools.datetimes import to_datetime
8080

81+
from pandas._typing import Level
8182
import pandas.io.formats.format as fmt
8283
import pandas.plotting
8384

@@ -4079,7 +4080,15 @@ def align(
40794080
broadcast_axis=broadcast_axis,
40804081
)
40814082

4082-
def rename(self, index=None, **kwargs):
4083+
def rename(
4084+
self,
4085+
index: Optional[
4086+
Union[Hashable, Mapping[Hashable, Hashable], Callable[[Hashable], Hashable]]
4087+
] = None,
4088+
copy: bool = True,
4089+
inplace: bool = False,
4090+
level: Optional[Level] = None,
4091+
) -> "Series":
40834092
"""
40844093
Alter Series index labels or name.
40854094

0 commit comments

Comments
 (0)