### Install asv Source: https://github.com/pydata/xarray/blob/main/doc/contribute/contributing.rst Install the airspeed-velocity benchmarking tool. ```shell python -m pip install asv ``` -------------------------------- ### Initialize Dataset for Plotting Source: https://github.com/pydata/xarray/blob/main/doc/user-guide/plotting.rst Load the tutorial scatter example dataset to use in subsequent plotting examples. ```python ds = xr.tutorial.scatter_example_dataset(seed=42) ds ``` -------------------------------- ### Import necessary libraries for duck array examples Source: https://github.com/pydata/xarray/blob/main/doc/internals/duck-arrays-integration.rst Setup imports for dask, xarray, numpy, and sparse to demonstrate duck array behavior. ```python import dask.array as da import xarray as xr import numpy as np import sparse ``` -------------------------------- ### Import required libraries Source: https://github.com/pydata/xarray/blob/main/doc/examples/multidimensional-coords.ipynb Initial setup for data analysis and visualization. ```python %matplotlib inline import numpy as np import pandas as pd import xarray as xr import cartopy.crs as ccrs from matplotlib import pyplot as plt ``` -------------------------------- ### Load tutorial dataset Source: https://github.com/pydata/xarray/blob/main/doc/examples/visualization_gallery.ipynb Loads the air temperature sample dataset for visualization examples. ```python ds = xr.tutorial.load_dataset("air_temperature") ``` -------------------------------- ### Install xarray with All Optional Dependencies (Pip) Source: https://github.com/pydata/xarray/blob/main/doc/getting-started-guide/installing.rst Install xarray along with all available optional dependencies for a complete feature set. ```bash $ python -m pip install "xarray[complete]" ``` -------------------------------- ### Install and Run Pre-commit Hooks Source: https://github.com/pydata/xarray/blob/main/doc/contribute/contributing.rst Use Pixi to enter the pre-commit environment and install git hooks. This ensures code quality checks are run automatically on commit. ```shell pixi shell -e pre-commit # enter the pre-commit environment pre-commit install # install the git hooks ``` ```shell pre-commit uninstall # uninstall the git hooks ``` -------------------------------- ### Example Remote Repository Output Source: https://github.com/pydata/xarray/blob/main/doc/contribute/contributing.rst Shows the expected output when listing remote repositories. ```text origin git@github.com:yourname/xarray.git (fetch) origin git@github.com:yourname/xarray.git (push) upstream git://github.com/pydata/xarray.git (fetch) upstream git://github.com/pydata/xarray.git (push) ``` -------------------------------- ### Import required libraries Source: https://github.com/pydata/xarray/blob/main/doc/examples/area_weighted_temperature.ipynb Initial setup for plotting and data manipulation. ```python %matplotlib inline import cartopy.crs as ccrs import matplotlib.pyplot as plt import numpy as np import xarray as xr ``` -------------------------------- ### Use fixtures for dependency setup Source: https://github.com/pydata/xarray/blob/main/xarray/tests/CLAUDE.md Use pytest fixtures to encapsulate setup logic for optional dependencies. ```python @pytest.fixture def dask_array(): pytest.importorskip("dask.array") import dask.array as da return da.from_array([1, 2, 3], chunks=2) ``` -------------------------------- ### Install pre-release version of xarray Source: https://github.com/pydata/xarray/blob/main/doc/whats-new.rst Instructions for installing a pre-release version of xarray using mamba and pip. ```bash mamba create -n python=3.10 xarray python -m pip install --pre --upgrade --no-deps xarray ``` -------------------------------- ### Install Development Versions Source: https://github.com/pydata/xarray/blob/main/doc/getting-started-guide/installing.rst Commands to install the latest development version of Xarray from GitHub or TestPyPI. ```bash $ python -m pip install git+https://github.com/pydata/xarray.git ``` ```bash $ python -m pip install --index-url https://test.pypi.org/simple --extra-index-url https://pypi.org/simple --pre xarray ``` -------------------------------- ### Initialize DataArray for indexing examples Source: https://github.com/pydata/xarray/blob/main/doc/user-guide/indexing.rst Creates a 4x3 DataArray with time and space coordinates for demonstration purposes. ```python da = xr.DataArray( np.random.rand(4, 3), [ ("time", pd.date_range("2000-01-01", periods=4)), ("space", ["IA", "IL", "IN"]), ], ) da[:2] ``` -------------------------------- ### Install xarray with Pip Source: https://github.com/pydata/xarray/blob/main/doc/getting-started-guide/installing.rst Install the base xarray package using pip. Ensure required dependencies like numpy and pandas are installed separately beforehand. ```bash $ python -m pip install xarray ``` -------------------------------- ### Install zarr with Conda Source: https://github.com/pydata/xarray/blob/main/doc/get-help/faq.rst Recommended way to install the zarr package using conda. ```bash conda install -c conda-forge zarr ``` -------------------------------- ### Install cfgrib via conda Source: https://github.com/pydata/xarray/blob/main/doc/get-help/faq.rst Command to install the cfgrib library. ```bash conda install -c conda-forge cfgrib ``` -------------------------------- ### Install xarray with Optional Acceleration Dependencies (Pip) Source: https://github.com/pydata/xarray/blob/main/doc/getting-started-guide/installing.rst Install xarray with optional dependencies that accelerate its performance, such as scipy and bottleneck. ```bash $ python -m pip install "xarray[accel]" ``` -------------------------------- ### Install xarray with Optional Visualization Dependencies (Pip) Source: https://github.com/pydata/xarray/blob/main/doc/getting-started-guide/installing.rst Install xarray with optional dependencies for visualization, including matplotlib and cartopy. ```bash $ python -m pip install "xarray[viz]" ``` -------------------------------- ### Generate and save example dataset Source: https://github.com/pydata/xarray/blob/main/doc/user-guide/dask.rst Creates a random Dataset and saves it to a temporary NetCDF file. ```python import os import tempfile tempdir = tempfile.TemporaryDirectory() np.random.seed(123456) # limit the amount of information printed to screen xr.set_options(display_expand_data=False) np.set_printoptions(precision=3, linewidth=100, threshold=10, edgeitems=2) ds = xr.Dataset( { "temperature": ( ("time", "latitude", "longitude"), np.random.randn(30, 180, 180), ), "time": pd.date_range("2015-01-01", periods=30), "longitude": np.arange(180), "latitude": np.arange(89.5, -90.5, -1), } ) ds.to_netcdf(os.path.join(tempdir.name, "example-data.nc")) ``` -------------------------------- ### Install scipy via conda Source: https://github.com/pydata/xarray/blob/main/doc/get-help/faq.rst Command to install the scipy library. ```bash conda install scipy ``` -------------------------------- ### Create a sparse matrix example Source: https://github.com/pydata/xarray/blob/main/doc/internals/duck-arrays-integration.rst Initialize a sparse COO matrix from a numpy array. ```python b = np.eye(10) b[[5, 7, 3, 0], [6, 8, 2, 9]] = 2 b = sparse.COO.from_numpy(b) b ``` -------------------------------- ### Install xarray with Optional Parallel Computing Dependencies (Pip) Source: https://github.com/pydata/xarray/blob/main/doc/getting-started-guide/installing.rst Install xarray with optional dependencies for parallel computing, primarily dask.array. ```bash $ python -m pip install "xarray[parallel]" ``` -------------------------------- ### Install xarray with Optional I/O Dependencies (Pip) Source: https://github.com/pydata/xarray/blob/main/doc/getting-started-guide/installing.rst Install xarray along with optional dependencies specifically for handling I/O operations, such as netCDF4 and h5netcdf. ```bash $ python -m pip install "xarray[io]" ``` -------------------------------- ### Example Git Status Output Source: https://github.com/pydata/xarray/blob/main/doc/contribute/contributing.rst Shows the expected output format after adding a new file. ```text # On branch shiny-new-feature # # modified: /relative/path/to/file-you-added.py # ``` -------------------------------- ### Create Dataset for Zarr example Source: https://github.com/pydata/xarray/blob/main/doc/user-guide/io.rst Defines a sample xarray Dataset for demonstration purposes. ```python ds = xr.Dataset( {"foo": (("x", "y"), np.random.rand(4, 5))}, coords={ "x": [10, 20, 30, 40], "y": pd.date_range("2000-01-01", periods=5), "z": ("x", list("abcd")), }, ) ``` -------------------------------- ### Configure Rolling Window Aggregations Source: https://github.com/pydata/xarray/blob/main/doc/user-guide/computation.rst Examples of configuring rolling windows with centering and minimum period requirements. ```python r = arr.rolling(y=3, center=True) r.mean() ``` ```python r = arr.rolling(y=3, min_periods=2) r.mean() ``` ```python r = arr.rolling(y=3, center=True, min_periods=2) r.mean() ``` -------------------------------- ### Install pre-commit hooks Source: https://github.com/pydata/xarray/blob/main/doc/contribute/contributing.rst Run this command from the repository root to automatically execute code quality and formatting checks before commits. ```bash pre-commit install ``` -------------------------------- ### Install xarray with Recommended Dependencies (Conda) Source: https://github.com/pydata/xarray/blob/main/doc/getting-started-guide/installing.rst Use this command to install xarray along with its core recommended dependencies like dask, netCDF4, and bottleneck using the conda-forge channel. ```bash $ conda install -c conda-forge xarray dask netCDF4 bottleneck ``` -------------------------------- ### Create Example Dataset and DataArray Source: https://github.com/pydata/xarray/blob/main/doc/user-guide/groupby.rst Generates a sample xarray Dataset and DataArray for demonstrating GroupBy operations. Requires numpy and xarray. ```python import numpy as np import pandas as pd import xarray as xr np.random.seed(123456) ds = xr.Dataset( {"foo": (("x", "y"), np.random.rand(4, 3))}, coords={"x": [10, 20, 30, 40], "letters": ("x", list("abba"))}, ) arr = ds["foo"] ds ``` -------------------------------- ### Create and display an xarray Dataset Source: https://github.com/pydata/xarray/blob/main/doc/user-guide/reshaping.rst This example demonstrates how to create an xarray Dataset with multiple variables and coordinates, and then displays it. This is a foundational step for many reshaping operations. ```python data = xr.Dataset( data_vars={"a": (("x", "y"), [[0, 1, 2], [3, 4, 5]]), "b": ("x", [6, 7])}, coords={"y": ["u", "v", "w"]}, ) data ``` -------------------------------- ### Pytest Test Execution Example Source: https://github.com/pydata/xarray/blob/main/doc/contribute/contributing.rst Example shell command to run pytest on a specific test file and view verbose output. ```shell ((xarray) $ pytest test_cool_feature.py -v ================================= test session starts ================================== platform darwin -- Python 3.10.6, pytest-7.2.0, pluggy-1.0.0 -- cachedir: .pytest_cache plugins: hypothesis-6.56.3, cov-4.0.0 collected 11 items xarray/tests/test_cool_feature.py::test_dtypes[int8] PASSED [ 9%] xarray/tests/test_cool_feature.py::test_dtypes[int16] PASSED [ 18%] xarray/tests/test_cool_feature.py::test_dtypes[int32] PASSED [ 27%] xarray/tests/test_cool_feature.py::test_dtypes[int64] PASSED [ 36%] xarray/tests/test_cool_feature.py::test_mark[float32] PASSED [ 45%] ``` -------------------------------- ### BASIC Indexing Example Source: https://github.com/pydata/xarray/blob/main/doc/internals/how-to-add-new-backend.rst Demonstrates basic indexing using numbers and slices. The `_raw_indexing_method` is called with different arguments to show its behavior. ```python backend_array._raw_indexing_method(()) ``` ```python backend_array._raw_indexing_method(1, 1) ``` ```python backend_array._raw_indexing_method(slice(0, 3), slice(2, 4)) ``` -------------------------------- ### Generate Xarray variable examples Source: https://github.com/pydata/xarray/blob/main/doc/user-guide/testing.rst Use the .example() method on a strategy to generate random Xarray variable objects. ```python import xarray.testing.strategies as xrst xrst.variables().example() ``` ```python xrst.variables().example() ``` ```python xrst.variables().example() ``` -------------------------------- ### Initialize Sparse COO array Source: https://github.com/pydata/xarray/blob/main/doc/user-guide/duckarrays.rst Setup imports and create a sparse COO array from a numpy identity matrix. ```python from sparse import COO import xarray as xr import numpy as np %xmode minimal ``` ```python x = np.eye(4, dtype=np.uint8) # create diagonal identity matrix s = COO.from_numpy(x) s ``` -------------------------------- ### Create a dask array example Source: https://github.com/pydata/xarray/blob/main/doc/internals/duck-arrays-integration.rst Initialize a dask array to be used within an Xarray Dataset. ```python a = da.linspace(0, 1, 20, chunks=2) a ``` -------------------------------- ### Weighted Groupby Sum Example Source: https://github.com/pydata/xarray/blob/main/design_notes/grouper_objects.md Illustrates the property that weighted sum should be identical to groupby sum. ```python gb_sum = ds.groupby(by).sum() weights = CustomGrouper.weights(by) weighted_sum = xr.dot(ds, weights) assert_identical(gb_sum, weighted_sum) ``` -------------------------------- ### Open Tutorial Dataset Source: https://github.com/pydata/xarray/blob/main/doc/user-guide/io.rst Load a sample dataset for demonstrating chunking and storage operations. ```python ds = xr.tutorial.open_dataset("rasm") ``` -------------------------------- ### Getting First or Last Example from Groupby Objects Source: https://github.com/pydata/xarray/blob/main/doc/whats-new.rst Use the `first` and `last` methods on groupby objects to extract the first or last element from each group along the specified axis. This is useful for summarizing grouped data. ```python array.groupby("time.day").first() ``` ```python array.resample("1D", dim="time", how="first") ``` -------------------------------- ### Initialize environment and dataset Source: https://github.com/pydata/xarray/blob/main/doc/examples/weather-data.ipynb Imports necessary libraries and generates a synthetic weather dataset with temperature minimums and maximums. ```python import numpy as np import pandas as pd import seaborn as sns import xarray as xr %matplotlib inline ``` ```python np.random.seed(123) xr.set_options(display_style="html") times = pd.date_range("2000-01-01", "2001-12-31", name="time") annual_cycle = np.sin(2 * np.pi * (times.dayofyear.values / 365.25 - 0.28)) base = 10 + 15 * annual_cycle.reshape(-1, 1) tmin_values = base + 3 * np.random.randn(annual_cycle.size, 3) tmax_values = base + 10 + 3 * np.random.randn(annual_cycle.size, 3) ds = xr.Dataset( { "tmin": (("time", "location"), tmin_values), "tmax": (("time", "location"), tmax_values), }, {"time": times, "location": ["IA", "IN", "IL"]}, ) ds ``` -------------------------------- ### Install h5netcdf via conda Source: https://github.com/pydata/xarray/blob/main/doc/get-help/faq.rst Command to install the h5netcdf library. ```bash conda install -c conda-forge h5netcdf ``` -------------------------------- ### Load Xarray tutorial dataset Source: https://github.com/pydata/xarray/blob/main/doc/examples/blank_template.ipynb Initializes the environment with Xarray, NumPy, and Pandas, then loads the air_temperature tutorial dataset. ```python import xarray as xr import numpy as np import pandas as pd ds = xr.tutorial.load_dataset("air_temperature") da = ds["air"] ``` -------------------------------- ### Building documentation locally Source: https://github.com/pydata/xarray/blob/main/doc/contribute/contributing.rst Generates the documentation site from the doc directory. ```bash make html ``` -------------------------------- ### Build documentation using Pixi Source: https://github.com/pydata/xarray/blob/main/doc/contribute/contributing.rst Commands to trigger the documentation build process or perform a clean build. ```bash pixi run doc ``` ```bash pixi run doc-clean ``` -------------------------------- ### Preview documentation in browser Source: https://github.com/pydata/xarray/blob/main/doc/contribute/contributing.rst Open a specific generated HTML file in a local browser from the documentation directory. ```bash google-chrome _build/html/quick-overview.html ``` -------------------------------- ### Initialize Next Release Section Source: https://github.com/pydata/xarray/blob/main/HOW_TO_RELEASE.md Template for adding the next release section to the whats-new.rst file. ```rst .. _whats-new.YYYY.MM.X+1: vYYYY.MM.X+1 (unreleased) ----------------------- New Features ~~~~~~~~~~~~ Breaking Changes ~~~~~~~~~~~~~~~~ Deprecations ~~~~~~~~~~~~ Bug Fixes ~~~~~~~~~ Documentation ~~~~~~~~~~~~~ Internal Changes ~~~~~~~~~~~~~~~~ ``` -------------------------------- ### Registering Xarray Backend Entrypoint in setup.cfg Source: https://github.com/pydata/xarray/blob/main/doc/internals/how-to-add-new-backend.rst Configure a custom xarray backend engine using the [options.entry_points] section in your setup.cfg file. This method is suitable for older setuptools-based projects. ```cfg [options.entry_points] xarray.backends = my_engine = my_package.my_module:MyBackendEntrypoint ``` -------------------------------- ### Run All Linters and Formatters Source: https://github.com/pydata/xarray/blob/main/CLAUDE.md Apply pre-commit hooks to check and format all files in the repository. This includes checks like ruff. ```bash pre-commit run --all-files ``` -------------------------------- ### Registering Xarray Backend Entrypoint in setup.py Source: https://github.com/pydata/xarray/blob/main/doc/internals/how-to-add-new-backend.rst Define a custom xarray backend engine within the entry_points argument of setuptools.setup in your setup.py file. This allows programmatic configuration of your backend's registration. ```python setuptools.setup( entry_points={ "xarray.backends": [ "my_engine=my_package.my_module:MyBackendEntrypoint" ], }, ) ``` -------------------------------- ### Initialize visualization environment Source: https://github.com/pydata/xarray/blob/main/doc/examples/visualization_gallery.ipynb Imports necessary libraries and configures the notebook environment for plotting. ```python import cartopy.crs as ccrs import matplotlib.pyplot as plt import xarray as xr %matplotlib inline ``` -------------------------------- ### BackendArray Subclass Example Source: https://github.com/pydata/xarray/blob/main/doc/internals/how-to-add-new-backend.rst An example implementation of a custom BackendArray subclass. It must define shape, dtype, and a thread-safe __getitem__ method, optionally using explicit_indexing_adapter for simplified indexing logic. ```python from xarray.backends import BackendArray class MyBackendArray(BackendArray): def __init__( self, shape, dtype, lock, # other backend specific keyword arguments ): self.shape = shape self.dtype = dtype self.lock = lock def __getitem__( self, key: xarray.core.indexing.ExplicitIndexer, ) -> np.typing.ArrayLike: return indexing.explicit_indexing_adapter( key, self.shape, indexing.IndexingSupport.BASIC, self._raw_indexing_method, ) def _raw_indexing_method(self, key: tuple) -> np.typing.ArrayLike: # thread safe method that access to data on disk with self.lock: ... return item ``` -------------------------------- ### Run Test Suite Source: https://github.com/pydata/xarray/blob/main/HOW_TO_RELEASE.md Execute the full test suite to ensure release stability. ```sh pytest ``` -------------------------------- ### Create MultiIndex DataArray Source: https://github.com/pydata/xarray/blob/main/doc/user-guide/indexing.rst Initializes a DataArray with a MultiIndex for advanced indexing examples. ```python midx = pd.MultiIndex.from_product([list("abc"), [0, 1]], names=("one", "two")) mda = xr.DataArray(np.random.rand(6, 3), [("x", midx), ("y", range(3))]) mda ``` -------------------------------- ### Import Required Libraries Source: https://github.com/pydata/xarray/blob/main/doc/user-guide/plotting.rst Standard imports required for Xarray plotting examples. ```python import cartopy.crs as ccrs import matplotlib.pyplot as plt import numpy as np import pandas as pd import xarray as xr ``` -------------------------------- ### Create a DataArray for Concatenation Source: https://github.com/pydata/xarray/blob/main/doc/user-guide/combining.rst This DataArray is used in subsequent examples to demonstrate concatenation. ```python da = xr.DataArray( np.arange(6).reshape(2, 3), [("x", ["a", "b"]), ("y", [10, 20, 30])] ) da.isel(y=slice(0, 1)) # same as da[:, :1] ``` -------------------------------- ### Importing Required Libraries Source: https://github.com/pydata/xarray/blob/main/doc/examples/monthly-means.ipynb Initializes the environment with necessary data analysis and plotting libraries. ```python %matplotlib inline import numpy as np import pandas as pd import xarray as xr import matplotlib.pyplot as plt ``` -------------------------------- ### Broadcasting by dimension name Source: https://github.com/pydata/xarray/blob/main/doc/user-guide/computation.rst Examples of automatic dimension expansion and reordering during binary operations. ```python a = xr.DataArray([1, 2], [("x", ["a", "b"])]) a ``` ```python b = xr.DataArray([-1, -2, -3], [("y", [10, 20, 30])]) b ``` ```python a * b ``` ```python c = xr.DataArray(np.arange(6).reshape(3, 2), [b["y"], a["x"]]) c ``` ```python a + c ``` ```python c - c.T ``` ```python a2, b2 = xr.broadcast(a, b) a2 ``` ```python b2 ``` -------------------------------- ### Commit Empty Whats-New Source: https://github.com/pydata/xarray/blob/main/HOW_TO_RELEASE.md Create and push a new branch to initialize the next release section in the documentation. ```sh git checkout -b empty-whatsnew-YYYY.MM.X+1 git commit -am "empty whatsnew" git push ``` -------------------------------- ### Custom Grouper Implementation Source: https://github.com/pydata/xarray/blob/main/design_notes/grouper_objects.md An example of a CustomGrouper subclass implementing the factorize and weights methods. ```python class CustomGrouper(Grouper): def factorize(self, by: DataArray): ... return codes, group_indices, unique_coord, full_index def weights(self, by: DataArray) -> DataArray: ... return weights ``` -------------------------------- ### List Remote Repositories Source: https://github.com/pydata/xarray/blob/main/doc/contribute/contributing.rst Display all configured remote repositories. ```bash git remote -v ``` -------------------------------- ### Create Dataset from Scratch with Dictionary Assignment Source: https://github.com/pydata/xarray/blob/main/doc/user-guide/data-structures.rst This snippet demonstrates building an xarray Dataset from scratch by assigning data variables and coordinates using dictionary-like syntax. It shows how to add multiple variables and coordinates. ```python ds = xr.Dataset() ds["temperature"] = (("loc", "instrument", "time"), temperature) ds["temperature_double"] = (("loc", "instrument", "time"), temperature * 2) ds["precipitation"] = (("loc", "instrument", "time"), precipitation) ds.coords["lat"] = (("loc",), lat) ds.coords["lon"] = (("loc",), lon) ds.coords["time"] = pd.date_range("2014-09-06", periods=4) ds.coords["reference_time"] = pd.Timestamp("2014-09-05") ``` -------------------------------- ### Show available benchmark results Source: https://github.com/pydata/xarray/blob/main/asv_bench/benchmarks/README_CI.md Use 'asv show' to list commits with available benchmark results on different machines and environments. ```bash $> asv show ``` -------------------------------- ### Load and Prepare Dataset Source: https://github.com/pydata/xarray/blob/main/doc/user-guide/plotting.rst Loads the air temperature tutorial dataset and converts Kelvin to Celsius. ```python airtemps = xr.tutorial.open_dataset("air_temperature") airtemps ``` ```python # Convert to celsius air = airtemps.air - 273.15 # copy attributes to get nice figure labels and change Kelvin to Celsius air.attrs = airtemps.air.attrs air.attrs["units"] = "deg C" ``` -------------------------------- ### Prepare temporary directory for Zarr store Source: https://github.com/pydata/xarray/blob/main/doc/user-guide/io.rst Sets up a temporary directory to store the Zarr data, ensuring cleanup. ```python import os.path import tempfile tempdir = tempfile.TemporaryDirectory() zarr_filename = os.path.join(tempdir.name, zarr_filename) ``` -------------------------------- ### BibTeX Entry for xarray Version Source: https://github.com/pydata/xarray/blob/main/doc/get-help/faq.rst Example BibTeX entry for citing a specific version of the xarray package. ```bibtex @misc{xarray_v0_8_0, author = {Stephan Hoyer and Clark Fitzgerald and Joe Hamman and others}, title = {xarray: v0.8.0}, month = aug, year = 2016, doi = {10.5281/zenodo.59499}, url = {https://doi.org/10.5281/zenodo.59499} } ``` -------------------------------- ### Boolean Weights for Grouping Source: https://github.com/pydata/xarray/blob/main/design_notes/grouper_objects.md Example of boolean weights for a given group array, representing a summarization matrix. ```python [[1, 0, 0, 1, 1], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0]] ``` -------------------------------- ### Create a Dataset with all values set to zero Source: https://github.com/pydata/xarray/blob/main/doc/user-guide/indexing.rst Initialize a Dataset with the same structure as an existing one, but with all values set to zero using xr.zeros_like(). This is useful for creating a template for new data. ```python ds_org = xr.tutorial.open_dataset("eraint_uvz").isel( latitude=slice(56, 59), longitude=slice(255, 258), level=0 ) # set all values to 0 ds = xr.zeros_like(ds_org) ds ``` -------------------------------- ### Visualize initial temperature data Source: https://github.com/pydata/xarray/blob/main/doc/examples/area_weighted_temperature.ipynb Plots the first time step of the temperature data using a Lambert Conformal projection. ```python projection = ccrs.LambertConformal(central_longitude=-95, central_latitude=45) f, ax = plt.subplots(subplot_kw=dict(projection=projection)) air.isel(time=0).plot(transform=ccrs.PlateCarree(), cbar_kwargs=dict(shrink=0.7)) ax.coastlines() ``` -------------------------------- ### Subsetting ROMS Data Source: https://github.com/pydata/xarray/blob/main/doc/examples/ROMS_ocean_model.ipynb Example command to subset a large ROMS dataset and save it as a local NetCDF file. ```python #open dataset ds = xr.open_dataset('/d2/shared/TXLA_ROMS/output_20yr_obc/2001/ocean_his_0015.nc') # Turn on chunking to activate dask and parallelize read/write. ds = ds.chunk({'ocean_time': 1}) # Pick out some of the variables that will be included as coordinates ds = ds.set_coords(['Cs_r', 'Cs_w', 'hc', 'h', 'Vtransform']) # Select a subset of variables. Salt will be visualized, zeta is used to # calculate the vertical coordinate variables = ['salt', 'zeta'] ds[variables].isel(ocean_time=slice(47, None, 7*24), xi_rho=slice(300, None)).to_netcdf('ROMS_example.nc', mode='w') ``` -------------------------------- ### Registering a ChunkManagerEntrypoint in setup.cfg Source: https://github.com/pydata/xarray/blob/main/doc/internals/chunked-arrays.rst Add an entry to the project's setup.cfg file to register a new chunk manager implementation with Xarray. ```ini [options.entry_points] xarray.chunkmanagers = dask = xarray.namedarray.daskmanager:DaskManager ``` -------------------------------- ### Reproduce bugs with a self-contained snippet Source: https://github.com/pydata/xarray/blob/main/doc/contribute/contributing.rst Use this template to provide a minimal, reproducible example when reporting bugs in xarray. ```python import xarray as xr ds = xr.Dataset(...) ... ``` -------------------------------- ### Load Example Dataset for Interpolation Source: https://github.com/pydata/xarray/blob/main/doc/examples/apply_ufunc_vectorize_1d.ipynb Loads the air temperature dataset and selects a small subset for demonstration. Ensures the 'lat' coordinate is sorted in ascending order, as required by np.interp. ```python import xarray as xr import numpy as np xr.set_options(display_style="html") # fancy HTML repr air = ( xr.tutorial.load_dataset("air_temperature") .air.sortby("lat") # np.interp needs coordinate in ascending order .isel(time=slice(4), lon=slice(3)) # choose a small subset for convenience ) air ``` -------------------------------- ### Convert DataArray to Iris Cube Source: https://github.com/pydata/xarray/blob/main/doc/user-guide/io.rst Converts an xarray DataArray to an Iris Cube object. Requires the Iris library to be installed. ```python da = xr.DataArray( np.random.rand(4, 5), dims=["x", "y"], coords=dict(x=[10, 20, 30, 40], y=pd.date_range("2000-01-01", periods=5)), ) cube = da.to_iris() print(cube) ``` -------------------------------- ### Open HDF5 file with h5netcdf engine Source: https://github.com/pydata/xarray/blob/main/doc/user-guide/io.rst Use this to open HDF5 files with xarray. Requires the 'h5netcdf' engine to be installed. ```python xr.open_dataset("/path/to/my/file.h5") ``` -------------------------------- ### DataArray with multiple coordinates Source: https://github.com/pydata/xarray/blob/main/design_notes/flexible_indexes_notes.md Example of a DataArray where multiple coordinates exist for a single dimension, illustrating the limitation of current indexing. ```python >>> da array([...]) Coordinates: * drainage_area (river_profile) float64 ... * chi (river_profile) float64 ... ``` -------------------------------- ### Run performance benchmarks Source: https://github.com/pydata/xarray/blob/main/doc/contribute/contributing.rst Execute continuous benchmarks comparing branches. ```shell asv continuous -f 1.1 upstream/main HEAD ``` ```shell asv continuous -f 1.1 -E virtualenv upstream/main HEAD ``` ```shell asv continuous -f 1.1 upstream/main HEAD -b ^groupby ``` ```shell asv continuous -f 1.1 upstream/main HEAD -b groupby.GroupByMethods ``` -------------------------------- ### Convert Iris Cube to DataArray Source: https://github.com/pydata/xarray/blob/main/doc/user-guide/io.rst Creates a new xarray DataArray object from an Iris Cube. Requires the Iris library to be installed. ```python da_cube = xr.DataArray.from_iris(cube) ``` -------------------------------- ### Displaying and listing keys in DataTree Source: https://github.com/pydata/xarray/blob/main/doc/user-guide/hierarchical-data.rst Create a DataTree with datasets and children, then print the tree structure and list all keys (both data variables and child nodes). ```python dt = xr.DataTree( dataset=xr.Dataset({"foo": 0, "bar": 1}), children={"a": xr.DataTree(), "b": xr.DataTree()}, ) print(dt) list(dt.keys()) ``` -------------------------------- ### Define cftime Time Axis Source: https://github.com/pydata/xarray/blob/main/doc/user-guide/weather-climate.rst Creates a time DataArray using cftime.datetime objects for non-standard calendars. Ensure cftime is installed. ```python import xarray as xr import numpy as np import pandas as pd import cftime time = xr.DataArray( xr.date_range("2000", periods=3, freq="MS", use_cftime=True), dims="time", ) ``` -------------------------------- ### Resample Dataset to Daily Mean Source: https://github.com/pydata/xarray/blob/main/doc/user-guide/dask.rst Resample a dataset to daily frequency and calculate the mean. This operation is faster when the 'flox' package is installed. ```python daily = ds.resample(time="D").mean() ``` -------------------------------- ### Vectorized Indexing on Dataset Source: https://github.com/pydata/xarray/blob/main/doc/user-guide/indexing.rst Applies vectorized indexing to an xarray Dataset using `isel`. The example converts a DataArray to a Dataset and then indexes it. ```python ds = da.to_dataset(name="bar") ds.isel(x=xr.DataArray([0, 1, 2], dims=["points"])) ```