{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Basic Computation\n", "\n", "In this lesson, we discuss how to do scientific computations with xarray\n", "objects. Our learning goals are as follows. By the end of the lesson, we will be\n", "able to:\n", "\n", "- Apply basic arithmetic and numpy functions to xarray DataArrays / Dataset.\n", "- Use Xarray's label-aware reduction operations (e.g. `mean`, `sum`) weighted\n", " reductions.\n", "- Apply arbitrary functions to Xarray data via `apply_ufunc`.\n", "- Use Xarray's broadcasting to compute on arrays of different dimensionality." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import xarray as xr\n", "import matplotlib.pyplot as plt\n", "\n", "# Ask Xarray to not show data values by default\n", "xr.set_options(display_expand_data=False)\n", "\n", "%config InlineBackend.figure_format='retina'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Example Dataset\n", "\n", "First we load a dataset. We will use the\n", "[NOAA Extended Reconstructed Sea Surface Temperature (ERSST) v5](https://www.ncei.noaa.gov/products/extended-reconstructed-sst)\n", "product, a widely used and trusted gridded compilation of of historical data going back to 1854." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ds = xr.tutorial.load_dataset(\"ersstv5\")\n", "ds" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's do some basic visualizations of the data, just to make sure it looks\n", "reasonable.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ds.sst.isel(time=0).plot(vmin=-2, vmax=30);" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Arithmetic\n", "\n", "Xarray dataarrays and datasets work seamlessly with arithmetic operators and\n", "numpy array functions.\n", "\n", "For example, imagine we want to convert the temperature (given in Celsius) to\n", "Kelvin:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "sst_kelvin = ds.sst + 273.15\n", "sst_kelvin" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The dimensions and coordinates were preserved following the operation.\n", "\n", "
units
attribute, which is used in plotting,\n",
" Xarray does not inherently understand units. However, xarray can integrate with pint, which provides full unit-aware operations. See pint-xarray for more.\n",
"