|
4 | 4 | Reshaping and reorganizing data
|
5 | 5 | ###############################
|
6 | 6 |
|
7 |
| -These methods allow you to reorganize |
| 7 | +These methods allow you to reorganize your data by changing dimensions, array shape, order of values, or indexes. |
8 | 8 |
|
9 | 9 | .. ipython:: python
|
10 | 10 | :suppress:
|
@@ -292,3 +292,54 @@ As a shortcut, you can refer to existing coordinates by name:
|
292 | 292 | ds.sortby("x")
|
293 | 293 | ds.sortby(["y", "x"])
|
294 | 294 | ds.sortby(["y", "x"], ascending=False)
|
| 295 | +
|
| 296 | +.. _reshape.coarsen: |
| 297 | + |
| 298 | +Reshaping via coarsen |
| 299 | +--------------------- |
| 300 | + |
| 301 | +Whilst :py:class:`~xarray.DataArray.coarsen` is normally used for reducing your data's resolution by applying a reduction function |
| 302 | +(see the :ref:`page on computation<compute.coarsen>`), |
| 303 | +it can also be used to reorganise your data without applying a computation via :py:meth:`~xarray.core.rolling.DataArrayCoarsen.construct`. |
| 304 | + |
| 305 | +Taking our example tutorial air temperature dataset over the Northern US |
| 306 | + |
| 307 | +.. ipython:: python |
| 308 | + :suppress: |
| 309 | +
|
| 310 | + # Use defaults so we don't get gridlines in generated docs |
| 311 | + import matplotlib as mpl |
| 312 | +
|
| 313 | + mpl.rcdefaults() |
| 314 | +
|
| 315 | +.. ipython:: python |
| 316 | +
|
| 317 | + air = xr.tutorial.open_dataset("air_temperature")["air"] |
| 318 | +
|
| 319 | + @savefig pre_coarsening.png |
| 320 | + air.isel(time=0).plot(x="lon", y="lat") |
| 321 | +
|
| 322 | +we can split this up into sub-regions of size ``(9, 18)`` points using :py:meth:`~xarray.core.rolling.DataArrayCoarsen.construct`: |
| 323 | + |
| 324 | +.. ipython:: python |
| 325 | +
|
| 326 | + regions = air.coarsen(lat=9, lon=18, boundary="pad").construct( |
| 327 | + lon=("x_coarse", "x_fine"), lat=("y_coarse", "y_fine") |
| 328 | + ) |
| 329 | + regions |
| 330 | +
|
| 331 | +9 new regions have been created, each of size 9 by 18 points. |
| 332 | +The ``boundary="pad"`` kwarg ensured that all regions are the same size even though the data does not evenly divide into these sizes. |
| 333 | + |
| 334 | +By plotting these 9 regions together via :ref:`faceting<plotting.faceting>` we can see how they relate to the original data. |
| 335 | + |
| 336 | +.. ipython:: python |
| 337 | +
|
| 338 | + @savefig post_coarsening.png |
| 339 | + regions.isel(time=0).plot( |
| 340 | + x="x_fine", y="y_fine", col="x_coarse", row="y_coarse", yincrease=False |
| 341 | + ) |
| 342 | +
|
| 343 | +We are now free to easily apply any custom computation to each coarsened region of our new dataarray. |
| 344 | +This would involve specifying that applied functions should act over the ``"x_fine"`` and ``"y_fine"`` dimensions, |
| 345 | +but broadcast over the ``"x_coarse"`` and ``"y_coarse"`` dimensions. |
0 commit comments