Skip to content

Commit 8434785

Browse files
author
Greg Behm
committed
[docs] add Dataset.assign_coords example (pydata#6336)
1 parent 6144c61 commit 8434785

File tree

1 file changed

+48
-1
lines changed

1 file changed

+48
-1
lines changed

xarray/core/common.py

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -450,7 +450,7 @@ def assign_coords(self, coords=None, **coords_kwargs):
450450
451451
Examples
452452
--------
453-
Convert longitude coordinates from 0-359 to -180-179:
453+
Convert `DataArray` longitude coordinates from 0-359 to -180-179:
454454
455455
>>> da = xr.DataArray(
456456
... np.random.rand(4),
@@ -490,6 +490,53 @@ def assign_coords(self, coords=None, **coords_kwargs):
490490
491491
>>> _ = da.assign_coords({"lon_2": ("lon", lon_2)})
492492
493+
Note the same method applies to `Dataset` objects.
494+
495+
Convert `Dataset` longitude coordinates from 0-359 to -180-179:
496+
497+
>>> np.random.seed(0)
498+
>>> ds = xr.Dataset(
499+
... data_vars=dict(
500+
... temperature=(["x", "y", "time"], 15 + 8 * np.random.randn(2, 2, 3)),
501+
... precipitation=(["x", "y", "time"], 10 * np.random.rand(2, 2, 3)),
502+
... ),
503+
... coords=dict(
504+
... lon=(["x", "y"], [[260.17, 260.68], [260.21, 260.77]]),
505+
... lat=(["x", "y"], [[42.25, 42.21], [42.63, 42.59]]),
506+
... time=pd.date_range("2014-09-06", periods=3),
507+
... reference_time=pd.Timestamp("2014-09-05")
508+
... ),
509+
... attrs=dict(description="Weather-related data"),
510+
... )
511+
>>> ds
512+
<xarray.Dataset>
513+
Dimensions: (x: 2, y: 2, time: 3)
514+
Coordinates:
515+
lon (x, y) float64 260.2 260.7 260.2 260.8
516+
lat (x, y) float64 42.25 42.21 42.63 42.59
517+
* time (time) datetime64[ns] 2014-09-06 2014-09-07 2014-09-08
518+
reference_time datetime64[ns] 2014-09-05
519+
Dimensions without coordinates: x, y
520+
Data variables:
521+
temperature (x, y, time) float64 29.11 18.2 22.83 ... 18.28 16.15 26.63
522+
precipitation (x, y, time) float64 5.68 9.256 0.7104 ... 7.992 4.615 7.805
523+
Attributes:
524+
description: Temperature data
525+
>>> ds.assign_coords(lon=(((ds.lon + 180) % 360) - 180))
526+
<xarray.Dataset>
527+
Dimensions: (x: 2, y: 2, time: 3)
528+
Coordinates:
529+
lon (x, y) float64 -99.83 -99.32 -99.79 -99.23
530+
lat (x, y) float64 42.25 42.21 42.63 42.59
531+
* time (time) datetime64[ns] 2014-09-06 2014-09-07 2014-09-08
532+
reference_time datetime64[ns] 2014-09-05
533+
Dimensions without coordinates: x, y
534+
Data variables:
535+
temperature (x, y, time) float64 29.11 18.2 22.83 ... 18.28 16.15 26.63
536+
precipitation (x, y, time) float64 5.68 9.256 0.7104 ... 7.992 4.615 7.805
537+
Attributes:
538+
description: Weather-related data
539+
493540
Notes
494541
-----
495542
Since ``coords_kwargs`` is a dictionary, the order of your arguments

0 commit comments

Comments
 (0)