Skip to content

Commit ab8ed31

Browse files
committed
REF: _get_axis, _get_axis_name, _get_axis_number
1 parent 4707d8e commit ab8ed31

File tree

7 files changed

+80
-51
lines changed

7 files changed

+80
-51
lines changed

pandas/core/computation/align.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ def _align_core_single_unary_op(
3838
def _zip_axes_from_type(
3939
typ: Type[FrameOrSeries], new_axes: Sequence[int]
4040
) -> Dict[str, int]:
41-
axes = {name: new_axes[i] for i, name in typ._AXIS_NAMES.items()}
41+
axes = {name: new_axes[i] for i, name in enumerate(typ._AXIS_ORDERS)}
4242
return axes
4343

4444

pandas/core/frame.py

+17-2
Original file line numberDiff line numberDiff line change
@@ -8787,8 +8787,11 @@ def isin(self, values) -> "DataFrame":
87878787
# ----------------------------------------------------------------------
87888788
# Add index and columns
87898789
_AXIS_ORDERS = ["index", "columns"]
8790-
_AXIS_NUMBERS = {"index": 0, "columns": 1}
8791-
_AXIS_NAMES = {0: "index", 1: "columns"}
8790+
_AXIS_TO_AXIS_NUMBER: Dict[Axis, int] = {
8791+
**NDFrame._AXIS_TO_AXIS_NUMBER,
8792+
1: 1,
8793+
"columns": 1,
8794+
}
87928795
_AXIS_REVERSED = True
87938796
_AXIS_LEN = len(_AXIS_ORDERS)
87948797
_info_axis_number = 1
@@ -8801,6 +8804,18 @@ def isin(self, values) -> "DataFrame":
88018804
axis=0, doc="The column labels of the DataFrame."
88028805
)
88038806

8807+
@property
8808+
def _AXIS_NUMBERS(self) -> Dict[str, int]:
8809+
""".. deprecated:: 1.1.0"""
8810+
super()._AXIS_NUMBERS
8811+
return {"index": 0, "columns": 1}
8812+
8813+
@property
8814+
def _AXIS_NAMES(self) -> Dict[int, str]:
8815+
""".. deprecated:: 1.1.0"""
8816+
super()._AXIS_NAMES
8817+
return {0: "index", 1: "columns"}
8818+
88048819
# ----------------------------------------------------------------------
88058820
# Add plotting methods to DataFrame
88068821
plot = CachedAccessor("plot", pandas.plotting.PlotAccessor)

pandas/core/generic.py

+38-35
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,6 @@
6767
is_dict_like,
6868
is_extension_array_dtype,
6969
is_float,
70-
is_integer,
7170
is_list_like,
7271
is_number,
7372
is_numeric_dtype,
@@ -302,19 +301,36 @@ def _data(self):
302301

303302
# ----------------------------------------------------------------------
304303
# Axis
305-
_AXIS_ALIASES = {"rows": 0}
306-
_AXIS_IALIASES = {0: "rows"}
307304
_stat_axis_number = 0
308305
_stat_axis_name = "index"
309306
_ix = None
310307
_AXIS_ORDERS: List[str]
311-
_AXIS_NUMBERS: Dict[str, int]
312-
_AXIS_NAMES: Dict[int, str]
308+
_AXIS_TO_AXIS_NUMBER: Dict[Axis, int] = {0: 0, "index": 0, "rows": 0}
313309
_AXIS_REVERSED: bool
314310
_info_axis_number: int
315311
_info_axis_name: str
316312
_AXIS_LEN: int
317313

314+
@property
315+
def _AXIS_NUMBERS(self) -> Dict[str, int]:
316+
""".. deprecated:: 1.1.0"""
317+
warnings.warn(
318+
"_AXIS_NUMBERS has been deprecated. Call ._get_axis_number instead",
319+
FutureWarning,
320+
stacklevel=3,
321+
)
322+
return {"index": 0}
323+
324+
@property
325+
def _AXIS_NAMES(self) -> Dict[int, str]:
326+
""".. deprecated:: 1.1.0"""
327+
warnings.warn(
328+
"_AXIS_NAMES has been deprecated. Call ._get_axis_name instead",
329+
FutureWarning,
330+
stacklevel=3,
331+
)
332+
return {0: "index"}
333+
318334
def _construct_axes_dict(self, axes=None, **kwargs):
319335
"""Return an axes dictionary for myself."""
320336
d = {a: self._get_axis(a) for a in (axes or self._AXIS_ORDERS)}
@@ -353,37 +369,24 @@ def _construct_axes_from_arguments(
353369
return axes, kwargs
354370

355371
@classmethod
356-
def _get_axis_number(cls, axis) -> int:
357-
axis = cls._AXIS_ALIASES.get(axis, axis)
358-
if is_integer(axis):
359-
if axis in cls._AXIS_NAMES:
360-
return axis
361-
else:
362-
try:
363-
return cls._AXIS_NUMBERS[axis]
364-
except KeyError:
365-
pass
366-
raise ValueError(f"No axis named {axis} for object type {cls.__name__}")
372+
def _get_axis_number(cls, axis: Axis) -> int:
373+
try:
374+
return cls._AXIS_TO_AXIS_NUMBER[axis]
375+
except KeyError:
376+
raise ValueError(f"No axis named {axis} for object type {cls.__name__}")
367377

368378
@classmethod
369-
def _get_axis_name(cls, axis) -> str:
370-
axis = cls._AXIS_ALIASES.get(axis, axis)
371-
if isinstance(axis, str):
372-
if axis in cls._AXIS_NUMBERS:
373-
return axis
374-
else:
375-
try:
376-
return cls._AXIS_NAMES[axis]
377-
except KeyError:
378-
pass
379-
raise ValueError(f"No axis named {axis} for object type {cls.__name__}")
379+
def _get_axis_name(cls, axis: Axis) -> str:
380+
axis_number = cls._get_axis_number(axis)
381+
return cls._AXIS_ORDERS[axis_number]
380382

381-
def _get_axis(self, axis) -> Index:
382-
name = self._get_axis_name(axis)
383-
return getattr(self, name)
383+
def _get_axis(self, axis: Axis) -> Index:
384+
axis_number = self._get_axis_number(axis)
385+
assert axis_number in {0, 1}
386+
return self.index if axis_number == 0 else self.columns
384387

385388
@classmethod
386-
def _get_block_manager_axis(cls, axis) -> int:
389+
def _get_block_manager_axis(cls, axis: Axis) -> int:
387390
"""Map the axis to the block_manager axis."""
388391
axis = cls._get_axis_number(axis)
389392
if cls._AXIS_REVERSED:
@@ -448,11 +451,11 @@ def _get_cleaned_column_resolvers(self) -> Dict[str, ABCSeries]:
448451
}
449452

450453
@property
451-
def _info_axis(self):
454+
def _info_axis(self) -> Index:
452455
return getattr(self, self._info_axis_name)
453456

454457
@property
455-
def _stat_axis(self):
458+
def _stat_axis(self) -> Index:
456459
return getattr(self, self._stat_axis_name)
457460

458461
@property
@@ -813,7 +816,7 @@ def squeeze(self, axis=None):
813816
>>> df_0a.squeeze()
814817
1
815818
"""
816-
axis = self._AXIS_NAMES if axis is None else (self._get_axis_number(axis),)
819+
axis = range(self._AXIS_LEN) if axis is None else (self._get_axis_number(axis),)
817820
return self.iloc[
818821
tuple(
819822
0 if i in axis and len(a) == 1 else slice(None)
@@ -1156,7 +1159,7 @@ class name
11561159
result = self if inplace else self.copy(deep=copy)
11571160

11581161
for axis in range(self._AXIS_LEN):
1159-
v = axes.get(self._AXIS_NAMES[axis])
1162+
v = axes.get(self._get_axis_name(axis))
11601163
if v is lib.no_default:
11611164
continue
11621165
non_mapper = is_scalar(v) or (is_list_like(v) and not is_dict_like(v))

pandas/core/series.py

-2
Original file line numberDiff line numberDiff line change
@@ -4614,8 +4614,6 @@ def to_period(self, freq=None, copy=True) -> "Series":
46144614
# ----------------------------------------------------------------------
46154615
# Add index
46164616
_AXIS_ORDERS = ["index"]
4617-
_AXIS_NUMBERS = {"index": 0}
4618-
_AXIS_NAMES = {0: "index"}
46194617
_AXIS_REVERSED = False
46204618
_AXIS_LEN = len(_AXIS_ORDERS)
46214619
_info_axis_number = 0

pandas/io/json/_json.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -867,12 +867,15 @@ def _convert_axes(self):
867867
"""
868868
Try to convert axes.
869869
"""
870-
for axis in self.obj._AXIS_NUMBERS.keys():
870+
for axis_name in self.obj._AXIS_ORDERS:
871871
new_axis, result = self._try_convert_data(
872-
axis, self.obj._get_axis(axis), use_dtypes=False, convert_dates=True
872+
name=axis_name,
873+
data=self.obj._get_axis(axis_name),
874+
use_dtypes=False,
875+
convert_dates=True,
873876
)
874877
if result:
875-
setattr(self.obj, axis, new_axis)
878+
setattr(self.obj, axis_name, new_axis)
876879

877880
def _try_convert_types(self):
878881
raise AbstractMethodError(self)

pandas/tests/generic/test_generic.py

+15-5
Original file line numberDiff line numberDiff line change
@@ -901,12 +901,22 @@ def test_pipe_tuple_error(self):
901901
@pytest.mark.parametrize("box", [pd.Series, pd.DataFrame])
902902
def test_axis_classmethods(self, box):
903903
obj = box(dtype=object)
904-
values = (
905-
list(box._AXIS_NAMES.keys())
906-
+ list(box._AXIS_NUMBERS.keys())
907-
+ list(box._AXIS_ALIASES.keys())
908-
)
904+
values = box._AXIS_TO_AXIS_NUMBER.keys()
909905
for v in values:
910906
assert obj._get_axis_number(v) == box._get_axis_number(v)
911907
assert obj._get_axis_name(v) == box._get_axis_name(v)
912908
assert obj._get_block_manager_axis(v) == box._get_block_manager_axis(v)
909+
910+
@pytest.mark.parametrize("box", [pd.Series, pd.DataFrame])
911+
def test_axis_names_deprecated(self, box):
912+
# GH33637
913+
obj = box(dtype=object)
914+
with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
915+
obj._AXIS_NAMES
916+
917+
@pytest.mark.parametrize("box", [pd.Series, pd.DataFrame])
918+
def test_axis_numbers_deprecated(self, box):
919+
# GH33637
920+
obj = box(dtype=object)
921+
with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
922+
obj._AXIS_NUMBERS

pandas/util/_validators.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -257,7 +257,7 @@ def validate_axis_style_args(data, args, kwargs, arg_name, method_name):
257257
# like out = {'index': foo, 'columns': bar}
258258

259259
# Start by validating for consistency
260-
if "axis" in kwargs and any(x in kwargs for x in data._AXIS_NUMBERS):
260+
if "axis" in kwargs and any(x in kwargs for x in data._AXIS_TO_AXIS_NUMBER):
261261
msg = "Cannot specify both 'axis' and any of 'index' or 'columns'."
262262
raise TypeError(msg)
263263

@@ -302,8 +302,8 @@ def validate_axis_style_args(data, args, kwargs, arg_name, method_name):
302302
"a 'TypeError'."
303303
)
304304
warnings.warn(msg.format(method_name=method_name), FutureWarning, stacklevel=4)
305-
out[data._AXIS_NAMES[0]] = args[0]
306-
out[data._AXIS_NAMES[1]] = args[1]
305+
out[data._get_axis_name(0)] = args[0]
306+
out[data._get_axis_name(1)] = args[1]
307307
else:
308308
msg = f"Cannot specify all of '{arg_name}', 'index', 'columns'."
309309
raise TypeError(msg)

0 commit comments

Comments
 (0)