Skip to content

Commit 08e43b9

Browse files
authored
Switch all methods to dim (#8982)
* Switch all methods to `dim`
1 parent fa8e90c commit 08e43b9

File tree

8 files changed

+99
-84
lines changed

8 files changed

+99
-84
lines changed

doc/whats-new.rst

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,10 @@ Internal Changes
7373
``xarray/testing/assertions`` for ``DataTree``. (:pull:`8967`)
7474
By `Owen Littlejohns <https://github.com/owenlittlejohns>`_ and
7575
`Tom Nicholas <https://github.com/TomNicholas>`_.
76+
- ``transpose``, ``set_dims``, ``stack`` & ``unstack`` now use a ``dim`` kwarg
77+
rather than ``dims`` or ``dimensions``. This is the final change to make xarray methods
78+
consistent with their use of ``dim``. Using the existing kwarg will raise a
79+
warning. By `Maximilian Roos <https://github.com/max-sixty>`_
7680

7781

7882
.. _whats-new.2024.03.0:

xarray/core/dataarray.py

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import datetime
44
import warnings
55
from collections.abc import Hashable, Iterable, Mapping, MutableMapping, Sequence
6+
from functools import partial
67
from os import PathLike
78
from typing import (
89
TYPE_CHECKING,
@@ -2808,12 +2809,13 @@ def reorder_levels(
28082809
ds = self._to_temp_dataset().reorder_levels(dim_order, **dim_order_kwargs)
28092810
return self._from_temp_dataset(ds)
28102811

2812+
@partial(deprecate_dims, old_name="dimensions")
28112813
def stack(
28122814
self,
2813-
dimensions: Mapping[Any, Sequence[Hashable]] | None = None,
2815+
dim: Mapping[Any, Sequence[Hashable]] | None = None,
28142816
create_index: bool | None = True,
28152817
index_cls: type[Index] = PandasMultiIndex,
2816-
**dimensions_kwargs: Sequence[Hashable],
2818+
**dim_kwargs: Sequence[Hashable],
28172819
) -> Self:
28182820
"""
28192821
Stack any number of existing dimensions into a single new dimension.
@@ -2823,7 +2825,7 @@ def stack(
28232825
28242826
Parameters
28252827
----------
2826-
dimensions : mapping of Hashable to sequence of Hashable
2828+
dim : mapping of Hashable to sequence of Hashable
28272829
Mapping of the form `new_name=(dim1, dim2, ...)`.
28282830
Names of new dimensions, and the existing dimensions that they
28292831
replace. An ellipsis (`...`) will be replaced by all unlisted dimensions.
@@ -2837,9 +2839,9 @@ def stack(
28372839
index_cls: class, optional
28382840
Can be used to pass a custom multi-index type. Must be an Xarray index that
28392841
implements `.stack()`. By default, a pandas multi-index wrapper is used.
2840-
**dimensions_kwargs
2841-
The keyword arguments form of ``dimensions``.
2842-
One of dimensions or dimensions_kwargs must be provided.
2842+
**dim_kwargs
2843+
The keyword arguments form of ``dim``.
2844+
One of dim or dim_kwargs must be provided.
28432845
28442846
Returns
28452847
-------
@@ -2874,10 +2876,10 @@ def stack(
28742876
DataArray.unstack
28752877
"""
28762878
ds = self._to_temp_dataset().stack(
2877-
dimensions,
2879+
dim,
28782880
create_index=create_index,
28792881
index_cls=index_cls,
2880-
**dimensions_kwargs,
2882+
**dim_kwargs,
28812883
)
28822884
return self._from_temp_dataset(ds)
28832885

@@ -3011,17 +3013,18 @@ def to_unstacked_dataset(self, dim: Hashable, level: int | Hashable = 0) -> Data
30113013
# unstacked dataset
30123014
return Dataset(data_dict)
30133015

3016+
@deprecate_dims
30143017
def transpose(
30153018
self,
3016-
*dims: Hashable,
3019+
*dim: Hashable,
30173020
transpose_coords: bool = True,
30183021
missing_dims: ErrorOptionsWithWarn = "raise",
30193022
) -> Self:
30203023
"""Return a new DataArray object with transposed dimensions.
30213024
30223025
Parameters
30233026
----------
3024-
*dims : Hashable, optional
3027+
*dim : Hashable, optional
30253028
By default, reverse the dimensions. Otherwise, reorder the
30263029
dimensions to this order.
30273030
transpose_coords : bool, default: True
@@ -3049,13 +3052,13 @@ def transpose(
30493052
numpy.transpose
30503053
Dataset.transpose
30513054
"""
3052-
if dims:
3053-
dims = tuple(infix_dims(dims, self.dims, missing_dims))
3054-
variable = self.variable.transpose(*dims)
3055+
if dim:
3056+
dim = tuple(infix_dims(dim, self.dims, missing_dims))
3057+
variable = self.variable.transpose(*dim)
30553058
if transpose_coords:
30563059
coords: dict[Hashable, Variable] = {}
30573060
for name, coord in self.coords.items():
3058-
coord_dims = tuple(dim for dim in dims if dim in coord.dims)
3061+
coord_dims = tuple(d for d in dim if d in coord.dims)
30593062
coords[name] = coord.variable.transpose(*coord_dims)
30603063
return self._replace(variable, coords)
30613064
else:

xarray/core/dataset.py

Lines changed: 21 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
MutableMapping,
1818
Sequence,
1919
)
20+
from functools import partial
2021
from html import escape
2122
from numbers import Number
2223
from operator import methodcaller
@@ -124,7 +125,7 @@
124125
from xarray.namedarray.parallelcompat import get_chunked_array_type, guess_chunkmanager
125126
from xarray.namedarray.pycompat import array_type, is_chunked_array
126127
from xarray.plot.accessor import DatasetPlotAccessor
127-
from xarray.util.deprecation_helpers import _deprecate_positional_args
128+
from xarray.util.deprecation_helpers import _deprecate_positional_args, deprecate_dims
128129

129130
if TYPE_CHECKING:
130131
from dask.dataframe import DataFrame as DaskDataFrame
@@ -5264,12 +5265,13 @@ def _stack_once(
52645265
new_variables, coord_names=new_coord_names, indexes=indexes
52655266
)
52665267

5268+
@partial(deprecate_dims, old_name="dimensions")
52675269
def stack(
52685270
self,
5269-
dimensions: Mapping[Any, Sequence[Hashable | ellipsis]] | None = None,
5271+
dim: Mapping[Any, Sequence[Hashable | ellipsis]] | None = None,
52705272
create_index: bool | None = True,
52715273
index_cls: type[Index] = PandasMultiIndex,
5272-
**dimensions_kwargs: Sequence[Hashable | ellipsis],
5274+
**dim_kwargs: Sequence[Hashable | ellipsis],
52735275
) -> Self:
52745276
"""
52755277
Stack any number of existing dimensions into a single new dimension.
@@ -5279,7 +5281,7 @@ def stack(
52795281
52805282
Parameters
52815283
----------
5282-
dimensions : mapping of hashable to sequence of hashable
5284+
dim : mapping of hashable to sequence of hashable
52835285
Mapping of the form `new_name=(dim1, dim2, ...)`. Names of new
52845286
dimensions, and the existing dimensions that they replace. An
52855287
ellipsis (`...`) will be replaced by all unlisted dimensions.
@@ -5295,9 +5297,9 @@ def stack(
52955297
index_cls: Index-class, default: PandasMultiIndex
52965298
Can be used to pass a custom multi-index type (must be an Xarray index that
52975299
implements `.stack()`). By default, a pandas multi-index wrapper is used.
5298-
**dimensions_kwargs
5299-
The keyword arguments form of ``dimensions``.
5300-
One of dimensions or dimensions_kwargs must be provided.
5300+
**dim_kwargs
5301+
The keyword arguments form of ``dim``.
5302+
One of dim or dim_kwargs must be provided.
53015303
53025304
Returns
53035305
-------
@@ -5308,9 +5310,9 @@ def stack(
53085310
--------
53095311
Dataset.unstack
53105312
"""
5311-
dimensions = either_dict_or_kwargs(dimensions, dimensions_kwargs, "stack")
5313+
dim = either_dict_or_kwargs(dim, dim_kwargs, "stack")
53125314
result = self
5313-
for new_dim, dims in dimensions.items():
5315+
for new_dim, dims in dim.items():
53145316
result = result._stack_once(dims, new_dim, index_cls, create_index)
53155317
return result
53165318

@@ -6218,9 +6220,10 @@ def drop_dims(
62186220
drop_vars = {k for k, v in self._variables.items() if set(v.dims) & drop_dims}
62196221
return self.drop_vars(drop_vars)
62206222

6223+
@deprecate_dims
62216224
def transpose(
62226225
self,
6223-
*dims: Hashable,
6226+
*dim: Hashable,
62246227
missing_dims: ErrorOptionsWithWarn = "raise",
62256228
) -> Self:
62266229
"""Return a new Dataset object with all array dimensions transposed.
@@ -6230,7 +6233,7 @@ def transpose(
62306233
62316234
Parameters
62326235
----------
6233-
*dims : hashable, optional
6236+
*dim : hashable, optional
62346237
By default, reverse the dimensions on each array. Otherwise,
62356238
reorder the dimensions to this order.
62366239
missing_dims : {"raise", "warn", "ignore"}, default: "raise"
@@ -6257,20 +6260,20 @@ def transpose(
62576260
numpy.transpose
62586261
DataArray.transpose
62596262
"""
6260-
# Raise error if list is passed as dims
6261-
if (len(dims) > 0) and (isinstance(dims[0], list)):
6262-
list_fix = [f"{repr(x)}" if isinstance(x, str) else f"{x}" for x in dims[0]]
6263+
# Raise error if list is passed as dim
6264+
if (len(dim) > 0) and (isinstance(dim[0], list)):
6265+
list_fix = [f"{repr(x)}" if isinstance(x, str) else f"{x}" for x in dim[0]]
62636266
raise TypeError(
6264-
f'transpose requires dims to be passed as multiple arguments. Expected `{", ".join(list_fix)}`. Received `{dims[0]}` instead'
6267+
f'transpose requires dim to be passed as multiple arguments. Expected `{", ".join(list_fix)}`. Received `{dim[0]}` instead'
62656268
)
62666269

62676270
# Use infix_dims to check once for missing dimensions
6268-
if len(dims) != 0:
6269-
_ = list(infix_dims(dims, self.dims, missing_dims))
6271+
if len(dim) != 0:
6272+
_ = list(infix_dims(dim, self.dims, missing_dims))
62706273

62716274
ds = self.copy()
62726275
for name, var in self._variables.items():
6273-
var_dims = tuple(dim for dim in dims if dim in (var.dims + (...,)))
6276+
var_dims = tuple(d for d in dim if d in (var.dims + (...,)))
62746277
ds._variables[name] = var.transpose(*var_dims)
62756278
return ds
62766279

0 commit comments

Comments
 (0)