Skip to content

Commit a5fe56a

Browse files
keewismax-sixty
authored andcommitted
Improve the documentation of swap_dims (#3331)
* add an example to DataArray.swap_dims (and fix the documented return type) * add an example to Dataset.swap_dims * fix some errors in the swapped array's repr * remove a newline * mention changes in whatsnew
1 parent 4617e68 commit a5fe56a

File tree

3 files changed

+45
-1
lines changed

3 files changed

+45
-1
lines changed

doc/whats-new.rst

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,10 @@ Bug fixes
2525
objects remain unaddressable by weakref in order to save memory.
2626
(:issue:`3317`) by `Guido Imperiale <https://github.com/crusaderky>`_.
2727

28+
Documentation
29+
~~~~~~~~~~~~~
30+
- Add examples for :py:meth:`Dataset.swap_dims` and :py:meth:`DataArray.swap_dims`.
31+
By `Justus Magin <https://github.com/keewis>`_.
2832

2933
.. _whats-new.0.13.0:
3034

xarray/core/dataarray.py

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1453,9 +1453,26 @@ def swap_dims(self, dims_dict: Mapping[Hashable, Hashable]) -> "DataArray":
14531453
14541454
Returns
14551455
-------
1456-
swapped : Dataset
1456+
swapped : DataArray
14571457
DataArray with swapped dimensions.
14581458
1459+
Examples
1460+
--------
1461+
>>> arr = xr.DataArray(data=[0, 1], dims="x",
1462+
coords={"x": ["a", "b"], "y": ("x", [0, 1])})
1463+
>>> arr
1464+
<xarray.DataArray (x: 2)>
1465+
array([0, 1])
1466+
Coordinates:
1467+
* x (x) <U1 'a' 'b'
1468+
y (x) int64 0 1
1469+
>>> arr.swap_dims({"x": "y"})
1470+
<xarray.DataArray (y: 2)>
1471+
array([0, 1])
1472+
Coordinates:
1473+
x (y) <U1 'a' 'b'
1474+
* y (y) int64 0 1
1475+
14591476
See Also
14601477
--------
14611478

xarray/core/dataset.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2679,6 +2679,29 @@ def swap_dims(
26792679
swapped : Dataset
26802680
Dataset with swapped dimensions.
26812681
2682+
Examples
2683+
--------
2684+
>>> ds = xr.Dataset(data_vars={"a": ("x", [5, 7]), "b": ("x", [0.1, 2.4])},
2685+
coords={"x": ["a", "b"], "y": ("x", [0, 1])})
2686+
>>> ds
2687+
<xarray.Dataset>
2688+
Dimensions: (x: 2)
2689+
Coordinates:
2690+
* x (x) <U1 'a' 'b'
2691+
y (x) int64 0 1
2692+
Data variables:
2693+
a (x) int64 5 7
2694+
b (x) float64 0.1 2.4
2695+
>>> ds.swap_dims({"x": "y"})
2696+
<xarray.Dataset>
2697+
Dimensions: (y: 2)
2698+
Coordinates:
2699+
x (y) <U1 'a' 'b'
2700+
* y (y) int64 0 1
2701+
Data variables:
2702+
a (y) int64 5 7
2703+
b (y) float64 0.1 2.4
2704+
26822705
See Also
26832706
--------
26842707

0 commit comments

Comments
 (0)