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: 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

Figure Settings#

# @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#

Tutorial slides#

These are the slides for the videos in all tutorials today

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([[[288.01373832, 285.37213432, 279.72736745, 275.27233949],
        [288.32675474, 275.88148274, 287.44044738, 277.21404075],
        [277.83781698, 279.11197138, 286.5603264 , 284.15156315]],

       [[292.7817499 , 282.40393901, 290.54953463, 289.29896415],
        [280.97962404, 296.99752164, 280.60597832, 281.73270755],
        [286.67164222, 288.54702452, 285.81796361, 284.8595902 ]],

       [[280.06231441, 296.73381467, 282.75226268, 285.23138019],
        [281.96310096, 288.8375047 , 281.4976446 , 281.72106991],
        [274.3652807 , 286.43088765, 289.5680532 , 283.30034089]],

       [[281.95725945, 284.15106937, 281.15445776, 288.92528944],
        [279.53500233, 286.90204739, 288.8050757 , 278.54528521],
        [281.5807734 , 283.19311914, 283.42738145, 276.77279335]],

       [[288.51755454, 284.02819238, 285.24082997, 279.36391865],
        [282.95296031, 286.29326535, 278.2996158 , 278.260263  ],
        [287.72932181, 284.3754806 , 280.74355261, 289.86430597]]])

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)>
array([[[288.01373832, 285.37213432, 279.72736745, 275.27233949],
        [288.32675474, 275.88148274, 287.44044738, 277.21404075],
        [277.83781698, 279.11197138, 286.5603264 , 284.15156315]],

       [[292.7817499 , 282.40393901, 290.54953463, 289.29896415],
        [280.97962404, 296.99752164, 280.60597832, 281.73270755],
        [286.67164222, 288.54702452, 285.81796361, 284.8595902 ]],

       [[280.06231441, 296.73381467, 282.75226268, 285.23138019],
        [281.96310096, 288.8375047 , 281.4976446 , 281.72106991],
        [274.3652807 , 286.43088765, 289.5680532 , 283.30034089]],

       [[281.95725945, 284.15106937, 281.15445776, 288.92528944],
        [279.53500233, 286.90204739, 288.8050757 , 278.54528521],
        [281.5807734 , 283.19311914, 283.42738145, 276.77279335]],

       [[288.51755454, 284.02819238, 285.24082997, 279.36391865],
        [282.95296031, 286.29326535, 278.2996158 , 278.260263  ],
        [287.72932181, 284.3754806 , 280.74355261, 289.86430597]]])
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)>
array([[[288.01373832, 285.37213432, 279.72736745, 275.27233949],
        [288.32675474, 275.88148274, 287.44044738, 277.21404075],
        [277.83781698, 279.11197138, 286.5603264 , 284.15156315]],

       [[292.7817499 , 282.40393901, 290.54953463, 289.29896415],
        [280.97962404, 296.99752164, 280.60597832, 281.73270755],
        [286.67164222, 288.54702452, 285.81796361, 284.8595902 ]],

       [[280.06231441, 296.73381467, 282.75226268, 285.23138019],
        [281.96310096, 288.8375047 , 281.4976446 , 281.72106991],
        [274.3652807 , 286.43088765, 289.5680532 , 283.30034089]],

       [[281.95725945, 284.15106937, 281.15445776, 288.92528944],
        [279.53500233, 286.90204739, 288.8050757 , 278.54528521],
        [281.5807734 , 283.19311914, 283.42738145, 276.77279335]],

       [[288.51755454, 284.02819238, 285.24082997, 279.36391865],
        [282.95296031, 286.29326535, 278.2996158 , 278.260263  ],
        [287.72932181, 284.3754806 , 280.74355261, 289.86430597]]])
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)>
array([[[288.01373832, 285.37213432, 279.72736745, 275.27233949],
        [288.32675474, 275.88148274, 287.44044738, 277.21404075],
        [277.83781698, 279.11197138, 286.5603264 , 284.15156315]],

       [[292.7817499 , 282.40393901, 290.54953463, 289.29896415],
        [280.97962404, 296.99752164, 280.60597832, 281.73270755],
        [286.67164222, 288.54702452, 285.81796361, 284.8595902 ]],

       [[280.06231441, 296.73381467, 282.75226268, 285.23138019],
        [281.96310096, 288.8375047 , 281.4976446 , 281.72106991],
        [274.3652807 , 286.43088765, 289.5680532 , 283.30034089]],

       [[281.95725945, 284.15106937, 281.15445776, 288.92528944],
        [279.53500233, 286.90204739, 288.8050757 , 278.54528521],
        [281.5807734 , 283.19311914, 283.42738145, 276.77279335]],

       [[288.51755454, 284.02819238, 285.24082997, 279.36391865],
        [282.95296031, 286.29326535, 278.2996158 , 278.260263  ],
        [287.72932181, 284.3754806 , 280.74355261, 289.86430597]]])
Coordinates:
  * time     (time) datetime64[ns] 2018-01-01 2018-01-02 ... 2018-01-05
  * lat      (lat) float64 25.0 40.0 55.0
  * lon      (lon) float64 -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)>
array([[[288.01373832, 285.37213432, 279.72736745, 275.27233949],
        [288.32675474, 275.88148274, 287.44044738, 277.21404075],
        [277.83781698, 279.11197138, 286.5603264 , 284.15156315]],

       [[292.7817499 , 282.40393901, 290.54953463, 289.29896415],
        [280.97962404, 296.99752164, 280.60597832, 281.73270755],
        [286.67164222, 288.54702452, 285.81796361, 284.8595902 ]],

       [[280.06231441, 296.73381467, 282.75226268, 285.23138019],
        [281.96310096, 288.8375047 , 281.4976446 , 281.72106991],
        [274.3652807 , 286.43088765, 289.5680532 , 283.30034089]],

       [[281.95725945, 284.15106937, 281.15445776, 288.92528944],
        [279.53500233, 286.90204739, 288.8050757 , 278.54528521],
        [281.5807734 , 283.19311914, 283.42738145, 276.77279335]],

       [[288.51755454, 284.02819238, 285.24082997, 279.36391865],
        [282.95296031, 286.29326535, 278.2996158 , 278.260263  ],
        [287.72932181, 284.3754806 , 280.74355261, 289.86430597]]])
Coordinates:
  * time     (time) datetime64[ns] 2018-01-01 2018-01-02 ... 2018-01-05
  * lat      (lat) float64 25.0 40.0 55.0
  * lon      (lon) float64 -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)>
array([[[14.86373832, 12.22213432,  6.57736745,  2.12233949],
        [15.17675474,  2.73148274, 14.29044738,  4.06404075],
        [ 4.68781698,  5.96197138, 13.4103264 , 11.00156315]],

       [[19.6317499 ,  9.25393901, 17.39953463, 16.14896415],
        [ 7.82962404, 23.84752164,  7.45597832,  8.58270755],
        [13.52164222, 15.39702452, 12.66796361, 11.7095902 ]],

       [[ 6.91231441, 23.58381467,  9.60226268, 12.08138019],
        [ 8.81310096, 15.6875047 ,  8.3476446 ,  8.57106991],
        [ 1.2152807 , 13.28088765, 16.4180532 , 10.15034089]],

       [[ 8.80725945, 11.00106937,  8.00445776, 15.77528944],
        [ 6.38500233, 13.75204739, 15.6550757 ,  5.39528521],
        [ 8.4307734 , 10.04311914, 10.27738145,  3.62279335]],

       [[15.36755454, 10.87819238, 12.09082997,  6.21391865],
        [ 9.80296031, 13.14326535,  5.1496158 ,  5.110263  ],
        [14.57932181, 11.2254806 ,  7.59355261, 16.71430597]]])
Coordinates:
  * time     (time) datetime64[ns] 2018-01-01 2018-01-02 ... 2018-01-05
  * lat      (lat) float64 25.0 40.0 55.0
  * lon      (lon) float64 -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)>
array([[[ 998.33005683, 1006.33699734,  999.06838855,  994.67289085],
        [ 999.77288674, 1001.36452555, 1000.66444248, 1003.87060908],
        [ 997.57333054,  995.98666699,  995.02209631,  996.71928778]],

       [[1006.09475639, 1005.40805487, 1001.41728836, 1007.91573974],
        [1000.16592034, 1001.65714387,  992.40930249,  999.12344646],
        [ 995.51777961,  993.49114494,  999.46486415,  996.58909758]],

       [[1009.61192284,  999.81792201, 1005.64069787,  998.65690359],
        [ 997.1379763 ,  996.04865105,  998.02828267, 1001.61973165],
        [ 997.71932382, 1005.72949418, 1007.15945345,  998.70107685]],

       [[1001.4889042 , 1000.13442936,  997.31712856,  997.94539106],
        [ 997.64338713, 1003.18704077, 1003.39649009,  999.27810513],
        [1002.12929028, 1001.49610893,  996.96034174,  997.44114834]],

       [[ 995.33923267, 1003.47820364,  995.99489166, 1001.9512489 ],
        [ 996.83602068, 1008.85984477, 1011.27226689, 1004.0695751 ],
        [1004.44980193,  996.74413092, 1004.77334484,  993.98331866]]])
Coordinates:
  * time     (time) datetime64[ns] 2018-01-01 2018-01-02 ... 2018-01-05
  * lat      (lat) float64 25.0 40.0 55.0
  * lon      (lon) float64 -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>
Dimensions:      (time: 5, lat: 3, lon: 4)
Coordinates:
  * time         (time) datetime64[ns] 2018-01-01 2018-01-02 ... 2018-01-05
  * lat          (lat) float64 25.0 40.0 55.0
  * lon          (lon) float64 -120.0 -100.0 -80.0 -60.0
Data variables:
    Temperature  (time, lat, lon) float64 288.0 285.4 279.7 ... 280.7 289.9
    Pressure     (time, lat, lon) float64 998.3 1.006e+03 ... 1.005e+03 994.0

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)>
array([[[ 998.33005683, 1006.33699734,  999.06838855,  994.67289085],
        [ 999.77288674, 1001.36452555, 1000.66444248, 1003.87060908],
        [ 997.57333054,  995.98666699,  995.02209631,  996.71928778]],

       [[1006.09475639, 1005.40805487, 1001.41728836, 1007.91573974],
        [1000.16592034, 1001.65714387,  992.40930249,  999.12344646],
        [ 995.51777961,  993.49114494,  999.46486415,  996.58909758]],

       [[1009.61192284,  999.81792201, 1005.64069787,  998.65690359],
        [ 997.1379763 ,  996.04865105,  998.02828267, 1001.61973165],
        [ 997.71932382, 1005.72949418, 1007.15945345,  998.70107685]],

       [[1001.4889042 , 1000.13442936,  997.31712856,  997.94539106],
        [ 997.64338713, 1003.18704077, 1003.39649009,  999.27810513],
        [1002.12929028, 1001.49610893,  996.96034174,  997.44114834]],

       [[ 995.33923267, 1003.47820364,  995.99489166, 1001.9512489 ],
        [ 996.83602068, 1008.85984477, 1011.27226689, 1004.0695751 ],
        [1004.44980193,  996.74413092, 1004.77334484,  993.98331866]]])
Coordinates:
  * time     (time) datetime64[ns] 2018-01-01 2018-01-02 ... 2018-01-05
  * lat      (lat) float64 25.0 40.0 55.0
  * lon      (lon) float64 -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)>
array([[[ 998.33005683, 1006.33699734,  999.06838855,  994.67289085],
        [ 999.77288674, 1001.36452555, 1000.66444248, 1003.87060908],
        [ 997.57333054,  995.98666699,  995.02209631,  996.71928778]],

       [[1006.09475639, 1005.40805487, 1001.41728836, 1007.91573974],
        [1000.16592034, 1001.65714387,  992.40930249,  999.12344646],
        [ 995.51777961,  993.49114494,  999.46486415,  996.58909758]],

       [[1009.61192284,  999.81792201, 1005.64069787,  998.65690359],
        [ 997.1379763 ,  996.04865105,  998.02828267, 1001.61973165],
        [ 997.71932382, 1005.72949418, 1007.15945345,  998.70107685]],

       [[1001.4889042 , 1000.13442936,  997.31712856,  997.94539106],
        [ 997.64338713, 1003.18704077, 1003.39649009,  999.27810513],
        [1002.12929028, 1001.49610893,  996.96034174,  997.44114834]],

       [[ 995.33923267, 1003.47820364,  995.99489166, 1001.9512489 ],
        [ 996.83602068, 1008.85984477, 1011.27226689, 1004.0695751 ],
        [1004.44980193,  996.74413092, 1004.77334484,  993.98331866]]])
Coordinates:
  * time     (time) datetime64[ns] 2018-01-01 2018-01-02 ... 2018-01-05
  * lat      (lat) float64 25.0 40.0 55.0
  * lon      (lon) float64 -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.