Skip to content

CLN: NDFrame.setup_axes #30064

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Dec 5, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,8 @@ class DataFrame(NDFrame):
2 7 8 9
"""

_typ = "dataframe"

@property
def _constructor(self) -> Type["DataFrame"]:
return DataFrame
Expand Down Expand Up @@ -8143,10 +8145,6 @@ def isin(self, values):

DataFrame._setup_axes(
["index", "columns"],
info_axis=1,
stat_axis=0,
axes_are_reversed=True,
aliases={"rows": 0},
docs={
"index": "The index (row labels) of the DataFrame.",
"columns": "The column labels of the DataFrame.",
Expand Down
87 changes: 28 additions & 59 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ class NDFrame(PandasObject, SelectionMixin):
_is_copy = None
_data: BlockManager
_attrs: Dict[Optional[Hashable], Any]
_typ: str

# ----------------------------------------------------------------------
# Constructors
Expand Down Expand Up @@ -283,71 +284,52 @@ def _constructor_expanddim(self):

# ----------------------------------------------------------------------
# Axis
_AXIS_ALIASES = {"rows": 0}
_AXIS_IALIASES = {0: "rows"}
_stat_axis_number = 0
_stat_axis_name = "index"
_ix = None
_AXIS_ORDERS: List[str]
_AXIS_NUMBERS: Dict[str, int]
_AXIS_NAMES: Dict[int, str]
_AXIS_REVERSED: bool
_info_axis_number: int
_info_axis_name: str
_AXIS_LEN: int

@classmethod
def _setup_axes(
cls,
axes,
info_axis=None,
stat_axis=None,
aliases=None,
axes_are_reversed=False,
build_axes=True,
ns=None,
docs=None,
):
def _setup_axes(cls, axes: List[str], docs: Dict[str, str]):
"""
Provide axes setup for the major PandasObjects.

Parameters
----------
axes : the names of the axes in order (lowest to highest)
info_axis_num : the axis of the selector dimension (int)
stat_axis_num : the number of axis for the default stats (int)
aliases : other names for a single axis (dict)
axes_are_reversed : bool
Whether to treat passed axes as reversed (DataFrame).
build_axes : setup the axis properties (default True)
docs : docstrings for the axis properties
"""
info_axis = len(axes) - 1
axes_are_reversed = len(axes) > 1

cls._AXIS_ORDERS = axes
cls._AXIS_NUMBERS = {a: i for i, a in enumerate(axes)}
cls._AXIS_LEN = len(axes)
cls._AXIS_ALIASES = aliases or dict()
cls._AXIS_IALIASES = {v: k for k, v in cls._AXIS_ALIASES.items()}
cls._AXIS_NAMES = dict(enumerate(axes))
cls._AXIS_REVERSED = axes_are_reversed

# typ
setattr(cls, "_typ", cls.__name__.lower())

# indexing support
cls._ix = None

if info_axis is not None:
cls._info_axis_number = info_axis
cls._info_axis_name = axes[info_axis]

if stat_axis is not None:
cls._stat_axis_number = stat_axis
cls._stat_axis_name = axes[stat_axis]
cls._info_axis_number = info_axis
cls._info_axis_name = axes[info_axis]

# setup the actual axis
if build_axes:

def set_axis(a, i):
setattr(cls, a, properties.AxisProperty(i, docs.get(a, a)))
cls._internal_names_set.add(a)

if axes_are_reversed:
m = cls._AXIS_LEN - 1
for i, a in cls._AXIS_NAMES.items():
set_axis(a, m - i)
else:
for i, a in cls._AXIS_NAMES.items():
set_axis(a, i)
def set_axis(a, i):
setattr(cls, a, properties.AxisProperty(i, docs.get(a, a)))
cls._internal_names_set.add(a)

assert not isinstance(ns, dict)
if axes_are_reversed:
for i, a in cls._AXIS_NAMES.items():
set_axis(a, 1 - i)
else:
for i, a in cls._AXIS_NAMES.items():
set_axis(a, i)

def _construct_axes_dict(self, axes=None, **kwargs):
"""Return an axes dictionary for myself."""
Expand Down Expand Up @@ -379,19 +361,6 @@ def _construct_axes_from_arguments(
args = list(args)
for a in self._AXIS_ORDERS:

# if we have an alias for this axis
alias = self._AXIS_IALIASES.get(a)
if alias is not None:
if a in kwargs:
if alias in kwargs:
raise TypeError(
f"arguments are mutually exclusive for [{a},{alias}]"
)
continue
if alias in kwargs:
kwargs[a] = kwargs.pop(alias)
continue

# look for a argument by position
if a not in kwargs:
try:
Expand Down
8 changes: 3 additions & 5 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,8 @@ class Series(base.IndexOpsMixin, generic.NDFrame):
Copy input data.
"""

_typ = "series"

_metadata: List[str] = []
_accessors = {"dt", "cat", "str", "sparse"}
_deprecations = (
Expand Down Expand Up @@ -4424,11 +4426,7 @@ def to_period(self, freq=None, copy=True):


Series._setup_axes(
["index"],
info_axis=0,
stat_axis=0,
aliases={"rows": 0},
docs={"index": "The index (axis labels) of the Series."},
["index"], docs={"index": "The index (axis labels) of the Series."},
)
Series._add_numeric_operations()
Series._add_series_only_operations()
Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/indexing/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1139,12 +1139,12 @@ def test_extension_array_cross_section_converts():
(
lambda x: x.loc,
AttributeError,
"type object 'NDFrame' has no attribute '_AXIS_ALIASES'",
"type object 'NDFrame' has no attribute '_AXIS_NAMES'",
),
(
lambda x: x.iloc,
AttributeError,
"type object 'NDFrame' has no attribute '_AXIS_ALIASES'",
"type object 'NDFrame' has no attribute '_AXIS_NAMES'",
),
],
)
Expand Down