Open In Colab   Open in Kaggle

Tutorial 1: Creating DataArrays and Datasets to Assess Global Climate Data#

Week 1, Day 1, Climate System Overview

Content creators: Sloane Garelick, Julia Kent

Content reviewers: Yosmely Bermúdez, Katrina Dobson, Younkap Nina Duplex, Danika Gupta, Maria Gonzalez, Will Gregory, Nahid Hasan, Sherry Mi, Beatriz Cosenza Muralles, Jenna Pearson, Chi Zhang, Ohad Zivan

Content editors: Jenna Pearson, Chi Zhang, Ohad Zivan

Production editors: Konstantine Tsafatinos, Wesley Banfield, Jenna Pearson, Chi Zhang, Ohad Zivan

Our 2023 Sponsors: NASA TOPS and Google DeepMind

project pythia#

Pythia credit: Rose, B. E. J., Kent, J., Tyle, K., Clyne, J., Banihirwe, A., Camron, D., May, R., Grover, M., Ford, R. R., Paul, K., Morley, J., Eroglu, O., Kailyn, L., & Zacharias, A. (2023). Pythia Foundations (Version v2023.05.01) https://zenodo.org/record/8065851

CMIP.png#

Tutorial Objectives#

As you just learned in the Introduction to Climate video, variations in global climate involve various forcings, feedbacks, and interactions between multiple processes and systems. Because of this complexity, global climate datasets are often very large with multiple dimensions and variables.

One useful computational tool for organizing, analyzing and interpreting large global datasets is Xarray, an open source project and Python package that makes working with labelled multi-dimensional arrays simple and efficient.

In this first tutorial, we will use the DataArray and Dataset objects, which are used to represent and manipulate spatial data, to practice organizing large global climate datasets and to understand variations in Earth’s climate system.

Setup#

Similar to numpy, np; pandas, pd; you may often encounter xarray imported within a shortened namespace as xr.

# imports
import numpy as np
import pandas as pd
import xarray as xr
import matplotlib.pyplot as plt

Install and import feedback gadget#

Hide code cell source
# @title Install and import feedback gadget

!pip3 install vibecheck datatops --quiet

from vibecheck import DatatopsContentReviewContainer
def content_review(notebook_section: str):
    return DatatopsContentReviewContainer(
        "",  # No text prompt
        notebook_section,
        {
            "url": "https://pmyvdlilci.execute-api.us-east-1.amazonaws.com/klab",
            "name": "comptools_4clim",
            "user_key": "l5jpxuee",
        },
    ).render()


feedback_prefix = "W1D1_T1"
[notice] A new release of pip is available: 23.0.1 -> 24.0
[notice] To update, run: pip install --upgrade pip

Figure Settings#

Hide code cell source
# @title Figure Settings
import ipywidgets as widgets  # interactive display

%config InlineBackend.figure_format = 'retina'
plt.style.use(
    "https://raw.githubusercontent.com/ClimateMatchAcademy/course-content/main/cma.mplstyle"
)

Video 1: Introduction to Climate#

Submit your feedback#

Hide code cell source
# @title Submit your feedback
content_review(f"{feedback_prefix}_Intro_to_Climate_Video")

Submit your feedback#

Hide code cell source
# @title Submit your feedback
content_review(f"{feedback_prefix}_Intro_to_Climate_Slides")

Introducing the DataArray and Dataset#

Xarray expands on the capabilities on NumPy arrays, providing a lot of streamlined data manipulation. It is similar in that respect to Pandas, but whereas Pandas excels at working with tabular data, Xarray is focused on N-dimensional arrays of data (i.e. grids). Its interface is based largely on the netCDF data model (variables, attributes, and dimensions), but it goes beyond the traditional netCDF interfaces to provide functionality similar to netCDF-java’s Common Data Model (CDM).

Section 1: Creation of a DataArray Object#

The DataArray is one of the basic building blocks of Xarray (see docs here). It provides a numpy.ndarray-like object that expands to provide two critical pieces of functionality:

  1. Coordinate names and values are stored with the data, making slicing and indexing much more powerful

  2. It has a built-in container for attributes

Here we’ll initialize a DataArray object by wrapping a plain NumPy array, and explore a few of its properties.

Section 1.1: Generate a Random Numpy Array#

For our first example, we’ll just create a random array of “temperature” data in units of Kelvin:

rand_data = 283 + 5 * np.random.randn(5, 3, 4)
rand_data
array([[[286.33762321, 281.26454484, 282.88395114, 272.64406248],
        [280.19214541, 278.95844909, 286.41936853, 285.53785117],
        [296.2834576 , 288.96557973, 277.78558383, 289.32585992]],

       [[285.64157551, 281.26857548, 288.01153589, 280.35971589],
        [278.83064153, 274.6140715 , 283.6915531 , 278.85468541],
        [273.62738272, 283.66181305, 279.52087606, 280.91149026]],

       [[282.40371167, 288.80616692, 279.78912953, 289.19636545],
        [288.54310486, 277.22402538, 285.75004082, 281.62462368],
        [280.08324604, 282.868057  , 279.18030917, 279.47989986]],

       [[276.04966675, 280.05144017, 267.31222465, 276.93149817],
        [287.62492628, 285.65599901, 277.30385223, 288.05713065],
        [290.8747816 , 282.35778868, 286.91063288, 278.6412487 ]],

       [[284.89136965, 282.00483247, 285.60419481, 285.40942612],
        [288.95611946, 278.97091407, 283.19303515, 282.37918077],
        [289.37802225, 286.93591077, 274.21114512, 284.2006467 ]]])

Section 1.2: Wrap the Array: First Attempt#

Now we create a basic DataArray just by passing our plain data as an input:

temperature = xr.DataArray(rand_data)
temperature
<xarray.DataArray (dim_0: 5, dim_1: 3, dim_2: 4)> Size: 480B
array([[[286.33762321, 281.26454484, 282.88395114, 272.64406248],
        [280.19214541, 278.95844909, 286.41936853, 285.53785117],
        [296.2834576 , 288.96557973, 277.78558383, 289.32585992]],

       [[285.64157551, 281.26857548, 288.01153589, 280.35971589],
        [278.83064153, 274.6140715 , 283.6915531 , 278.85468541],
        [273.62738272, 283.66181305, 279.52087606, 280.91149026]],

       [[282.40371167, 288.80616692, 279.78912953, 289.19636545],
        [288.54310486, 277.22402538, 285.75004082, 281.62462368],
        [280.08324604, 282.868057  , 279.18030917, 279.47989986]],

       [[276.04966675, 280.05144017, 267.31222465, 276.93149817],
        [287.62492628, 285.65599901, 277.30385223, 288.05713065],
        [290.8747816 , 282.35778868, 286.91063288, 278.6412487 ]],

       [[284.89136965, 282.00483247, 285.60419481, 285.40942612],
        [288.95611946, 278.97091407, 283.19303515, 282.37918077],
        [289.37802225, 286.93591077, 274.21114512, 284.2006467 ]]])
Dimensions without coordinates: dim_0, dim_1, dim_2

Note two things:

  1. Xarray generates some basic dimension names for us (dim_0, dim_1, dim_2). We’ll improve this with better names in the next example.

  2. Wrapping the numpy array in a DataArray gives us a rich display in the notebook! (Try clicking the array symbol to expand or collapse the view)

Section 1.3: Assign Dimension Names#

Much of the power of Xarray comes from making use of named dimensions. So let’s add some more useful names! We can do that by passing an ordered list of names using the keyword argument dims:

temperature = xr.DataArray(rand_data, dims=["time", "lat", "lon"])
temperature
<xarray.DataArray (time: 5, lat: 3, lon: 4)> Size: 480B
array([[[286.33762321, 281.26454484, 282.88395114, 272.64406248],
        [280.19214541, 278.95844909, 286.41936853, 285.53785117],
        [296.2834576 , 288.96557973, 277.78558383, 289.32585992]],

       [[285.64157551, 281.26857548, 288.01153589, 280.35971589],
        [278.83064153, 274.6140715 , 283.6915531 , 278.85468541],
        [273.62738272, 283.66181305, 279.52087606, 280.91149026]],

       [[282.40371167, 288.80616692, 279.78912953, 289.19636545],
        [288.54310486, 277.22402538, 285.75004082, 281.62462368],
        [280.08324604, 282.868057  , 279.18030917, 279.47989986]],

       [[276.04966675, 280.05144017, 267.31222465, 276.93149817],
        [287.62492628, 285.65599901, 277.30385223, 288.05713065],
        [290.8747816 , 282.35778868, 286.91063288, 278.6412487 ]],

       [[284.89136965, 282.00483247, 285.60419481, 285.40942612],
        [288.95611946, 278.97091407, 283.19303515, 282.37918077],
        [289.37802225, 286.93591077, 274.21114512, 284.2006467 ]]])
Dimensions without coordinates: time, lat, lon

This is already an improvement over a NumPy array because we have names for each of the dimensions (or axes). Even better, we can associate arrays representing the values for the coordinates for each of these dimensions with the data when we create the DataArray. We’ll see this in the next example.

Section 2: Create a DataArray with Named Coordinates#

Section 2.1: Make Time and Space Coordinates#

Here we will use Pandas to create an array of datetime data, which we will then use to create a DataArray with a named coordinate time.

times_index = pd.date_range("2018-01-01", periods=5)
times_index
DatetimeIndex(['2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04',
               '2018-01-05'],
              dtype='datetime64[ns]', freq='D')

We’ll also create arrays to represent sample longitude and latitude:

lons = np.linspace(-120, -60, 4)
lats = np.linspace(25, 55, 3)

Section 2.1.1: Initialize the DataArray with Complete Coordinate Info#

When we create the DataArray instance, we pass in the arrays we just created:

temperature = xr.DataArray(
    rand_data, coords=[times_index, lats, lons], dims=["time", "lat", "lon"]
)
temperature
<xarray.DataArray (time: 5, lat: 3, lon: 4)> Size: 480B
array([[[286.33762321, 281.26454484, 282.88395114, 272.64406248],
        [280.19214541, 278.95844909, 286.41936853, 285.53785117],
        [296.2834576 , 288.96557973, 277.78558383, 289.32585992]],

       [[285.64157551, 281.26857548, 288.01153589, 280.35971589],
        [278.83064153, 274.6140715 , 283.6915531 , 278.85468541],
        [273.62738272, 283.66181305, 279.52087606, 280.91149026]],

       [[282.40371167, 288.80616692, 279.78912953, 289.19636545],
        [288.54310486, 277.22402538, 285.75004082, 281.62462368],
        [280.08324604, 282.868057  , 279.18030917, 279.47989986]],

       [[276.04966675, 280.05144017, 267.31222465, 276.93149817],
        [287.62492628, 285.65599901, 277.30385223, 288.05713065],
        [290.8747816 , 282.35778868, 286.91063288, 278.6412487 ]],

       [[284.89136965, 282.00483247, 285.60419481, 285.40942612],
        [288.95611946, 278.97091407, 283.19303515, 282.37918077],
        [289.37802225, 286.93591077, 274.21114512, 284.2006467 ]]])
Coordinates:
  * time     (time) datetime64[ns] 40B 2018-01-01 2018-01-02 ... 2018-01-05
  * lat      (lat) float64 24B 25.0 40.0 55.0
  * lon      (lon) float64 32B -120.0 -100.0 -80.0 -60.0

Section 2.1.2: Set Useful Attributes#

We can also set some attribute metadata, which will help provide clear descriptions of the data. In this case, we can specify that we’re looking at ‘air_temperature’ data and the units are ‘kelvin’.

temperature.attrs["units"] = "kelvin"
temperature.attrs["standard_name"] = "air_temperature"

temperature
<xarray.DataArray (time: 5, lat: 3, lon: 4)> Size: 480B
array([[[286.33762321, 281.26454484, 282.88395114, 272.64406248],
        [280.19214541, 278.95844909, 286.41936853, 285.53785117],
        [296.2834576 , 288.96557973, 277.78558383, 289.32585992]],

       [[285.64157551, 281.26857548, 288.01153589, 280.35971589],
        [278.83064153, 274.6140715 , 283.6915531 , 278.85468541],
        [273.62738272, 283.66181305, 279.52087606, 280.91149026]],

       [[282.40371167, 288.80616692, 279.78912953, 289.19636545],
        [288.54310486, 277.22402538, 285.75004082, 281.62462368],
        [280.08324604, 282.868057  , 279.18030917, 279.47989986]],

       [[276.04966675, 280.05144017, 267.31222465, 276.93149817],
        [287.62492628, 285.65599901, 277.30385223, 288.05713065],
        [290.8747816 , 282.35778868, 286.91063288, 278.6412487 ]],

       [[284.89136965, 282.00483247, 285.60419481, 285.40942612],
        [288.95611946, 278.97091407, 283.19303515, 282.37918077],
        [289.37802225, 286.93591077, 274.21114512, 284.2006467 ]]])
Coordinates:
  * time     (time) datetime64[ns] 40B 2018-01-01 2018-01-02 ... 2018-01-05
  * lat      (lat) float64 24B 25.0 40.0 55.0
  * lon      (lon) float64 32B -120.0 -100.0 -80.0 -60.0
Attributes:
    units:          kelvin
    standard_name:  air_temperature

Section 2.1.3: Attributes Are Not Preserved by Default!#

Notice what happens if we perform a mathematical operaton with the DataArray: the coordinate values persist, but the attributes are lost. This is done because it is very challenging to know if the attribute metadata is still correct or appropriate after arbitrary arithmetic operations.

To illustrate this, we’ll do a simple unit conversion from Kelvin to Celsius:

temperature_in_celsius = temperature - 273.15
temperature_in_celsius
<xarray.DataArray (time: 5, lat: 3, lon: 4)> Size: 480B
array([[[13.18762321,  8.11454484,  9.73395114, -0.50593752],
        [ 7.04214541,  5.80844909, 13.26936853, 12.38785117],
        [23.1334576 , 15.81557973,  4.63558383, 16.17585992]],

       [[12.49157551,  8.11857548, 14.86153589,  7.20971589],
        [ 5.68064153,  1.4640715 , 10.5415531 ,  5.70468541],
        [ 0.47738272, 10.51181305,  6.37087606,  7.76149026]],

       [[ 9.25371167, 15.65616692,  6.63912953, 16.04636545],
        [15.39310486,  4.07402538, 12.60004082,  8.47462368],
        [ 6.93324604,  9.718057  ,  6.03030917,  6.32989986]],

       [[ 2.89966675,  6.90144017, -5.83777535,  3.78149817],
        [14.47492628, 12.50599901,  4.15385223, 14.90713065],
        [17.7247816 ,  9.20778868, 13.76063288,  5.4912487 ]],

       [[11.74136965,  8.85483247, 12.45419481, 12.25942612],
        [15.80611946,  5.82091407, 10.04303515,  9.22918077],
        [16.22802225, 13.78591077,  1.06114512, 11.0506467 ]]])
Coordinates:
  * time     (time) datetime64[ns] 40B 2018-01-01 2018-01-02 ... 2018-01-05
  * lat      (lat) float64 24B 25.0 40.0 55.0
  * lon      (lon) float64 32B -120.0 -100.0 -80.0 -60.0

We usually wish to keep metadata with our dataset, even after manipulating the data. For example it can tell us what the units are of a variable of interest. So when you perform operations on your data, make sure to check that all the information you want is carried over. If it isn’t, you can add it back in following the instructions in the section before this. For an in-depth discussion of how Xarray handles metadata, you can find more information in the Xarray documents here.

Section 3: The Dataset: a Container for DataArrays with Shared Coordinates#

Along with DataArray, the other key object type in Xarray is the Dataset, which is a dictionary-like container that holds one or more DataArrays, which can also optionally share coordinates (see docs here).

The most common way to create a Dataset object is to load data from a file (which we will practice in a later tutorial). Here, instead, we will create another DataArray and combine it with our temperature data.

This will illustrate how the information about common coordinate axes is used.

Section 3.1: Create a Pressure DataArray Using the Same Coordinates#

For our next DataArry example, we’ll create a random array of pressure data in units of hectopascal (hPa). This code mirrors how we created the temperature object above.

pressure_data = 1000.0 + 5 * np.random.randn(5, 3, 4)
pressure = xr.DataArray(
    pressure_data, coords=[times_index, lats, lons], dims=["time", "lat", "lon"]
)
pressure.attrs["units"] = "hPa"
pressure.attrs["standard_name"] = "air_pressure"

pressure
<xarray.DataArray (time: 5, lat: 3, lon: 4)> Size: 480B
array([[[ 995.27205381,  989.66268838,  992.55604714,  994.30116852],
        [ 998.8708526 , 1002.35098089, 1000.58559962, 1003.00649956],
        [1007.32376906,  993.29930777, 1000.44658838, 1005.86154051]],

       [[1000.85752513,  990.9791688 , 1005.9792341 , 1000.31722447],
        [ 996.20744937,  997.11404447,  997.37470221, 1002.54014557],
        [1002.21242253, 1003.88420848,  995.97244811,  998.69114962]],

       [[1004.95331956, 1001.28029533, 1000.58985075,  996.81391828],
        [1002.08828219, 1003.04646822, 1004.80638721,  996.99508145],
        [ 993.2571332 ,  996.18142765, 1007.30886754, 1005.29445805]],

       [[1010.19188661,  999.80058726, 1000.64512874, 1012.15680609],
        [1002.67324466, 1001.33112319, 1001.72399487, 1001.72690641],
        [ 996.03684363, 1004.99144929,  996.73557905,  993.46809325]],

       [[1004.40781043, 1000.53183025,  997.49655587, 1004.8620557 ],
        [1008.18345987, 1000.37776039,  998.89614042, 1000.86157161],
        [1007.91392078,  992.71639832, 1001.27634784, 1005.19071473]]])
Coordinates:
  * time     (time) datetime64[ns] 40B 2018-01-01 2018-01-02 ... 2018-01-05
  * lat      (lat) float64 24B 25.0 40.0 55.0
  * lon      (lon) float64 32B -120.0 -100.0 -80.0 -60.0
Attributes:
    units:          hPa
    standard_name:  air_pressure

Section 3.2: Create a Dataset Object#

Each DataArray in our Dataset needs a name!

The most straightforward way to create a Dataset with our temperature and pressure arrays is to pass a dictionary using the keyword argument data_vars:

ds = xr.Dataset(data_vars={"Temperature": temperature, "Pressure": pressure})
ds
<xarray.Dataset> Size: 1kB
Dimensions:      (time: 5, lat: 3, lon: 4)
Coordinates:
  * time         (time) datetime64[ns] 40B 2018-01-01 2018-01-02 ... 2018-01-05
  * lat          (lat) float64 24B 25.0 40.0 55.0
  * lon          (lon) float64 32B -120.0 -100.0 -80.0 -60.0
Data variables:
    Temperature  (time, lat, lon) float64 480B 286.3 281.3 282.9 ... 274.2 284.2
    Pressure     (time, lat, lon) float64 480B 995.3 989.7 ... 1.005e+03

Notice that the Dataset object ds is aware that both data arrays sit on the same coordinate axes.

Section 3.3: Access Data Variables and Coordinates in a Dataset#

We can pull out any of the individual DataArray objects in a few different ways.

Using the “dot” notation:

ds.Pressure
<xarray.DataArray 'Pressure' (time: 5, lat: 3, lon: 4)> Size: 480B
array([[[ 995.27205381,  989.66268838,  992.55604714,  994.30116852],
        [ 998.8708526 , 1002.35098089, 1000.58559962, 1003.00649956],
        [1007.32376906,  993.29930777, 1000.44658838, 1005.86154051]],

       [[1000.85752513,  990.9791688 , 1005.9792341 , 1000.31722447],
        [ 996.20744937,  997.11404447,  997.37470221, 1002.54014557],
        [1002.21242253, 1003.88420848,  995.97244811,  998.69114962]],

       [[1004.95331956, 1001.28029533, 1000.58985075,  996.81391828],
        [1002.08828219, 1003.04646822, 1004.80638721,  996.99508145],
        [ 993.2571332 ,  996.18142765, 1007.30886754, 1005.29445805]],

       [[1010.19188661,  999.80058726, 1000.64512874, 1012.15680609],
        [1002.67324466, 1001.33112319, 1001.72399487, 1001.72690641],
        [ 996.03684363, 1004.99144929,  996.73557905,  993.46809325]],

       [[1004.40781043, 1000.53183025,  997.49655587, 1004.8620557 ],
        [1008.18345987, 1000.37776039,  998.89614042, 1000.86157161],
        [1007.91392078,  992.71639832, 1001.27634784, 1005.19071473]]])
Coordinates:
  * time     (time) datetime64[ns] 40B 2018-01-01 2018-01-02 ... 2018-01-05
  * lat      (lat) float64 24B 25.0 40.0 55.0
  * lon      (lon) float64 32B -120.0 -100.0 -80.0 -60.0
Attributes:
    units:          hPa
    standard_name:  air_pressure

… or using dictionary access like this:

ds["Pressure"]
<xarray.DataArray 'Pressure' (time: 5, lat: 3, lon: 4)> Size: 480B
array([[[ 995.27205381,  989.66268838,  992.55604714,  994.30116852],
        [ 998.8708526 , 1002.35098089, 1000.58559962, 1003.00649956],
        [1007.32376906,  993.29930777, 1000.44658838, 1005.86154051]],

       [[1000.85752513,  990.9791688 , 1005.9792341 , 1000.31722447],
        [ 996.20744937,  997.11404447,  997.37470221, 1002.54014557],
        [1002.21242253, 1003.88420848,  995.97244811,  998.69114962]],

       [[1004.95331956, 1001.28029533, 1000.58985075,  996.81391828],
        [1002.08828219, 1003.04646822, 1004.80638721,  996.99508145],
        [ 993.2571332 ,  996.18142765, 1007.30886754, 1005.29445805]],

       [[1010.19188661,  999.80058726, 1000.64512874, 1012.15680609],
        [1002.67324466, 1001.33112319, 1001.72399487, 1001.72690641],
        [ 996.03684363, 1004.99144929,  996.73557905,  993.46809325]],

       [[1004.40781043, 1000.53183025,  997.49655587, 1004.8620557 ],
        [1008.18345987, 1000.37776039,  998.89614042, 1000.86157161],
        [1007.91392078,  992.71639832, 1001.27634784, 1005.19071473]]])
Coordinates:
  * time     (time) datetime64[ns] 40B 2018-01-01 2018-01-02 ... 2018-01-05
  * lat      (lat) float64 24B 25.0 40.0 55.0
  * lon      (lon) float64 32B -120.0 -100.0 -80.0 -60.0
Attributes:
    units:          hPa
    standard_name:  air_pressure

We’ll return to the Dataset object when we start loading data from files in later tutorials today.

Summary#

In this initial tutorial, the DataArray and Dataset objects were utilized to create and explore synthetic examples of climate data.

Resources#

Code and data for this tutorial is based on existing content from Project Pythia.