{ "cells": [ { "cell_type": "markdown", "id": "b1eefe41", "metadata": {}, "source": [ "# 4. Conditional Control of `datetime` Index" ] }, { "cell_type": "markdown", "id": "ae5b58b4", "metadata": {}, "source": [ "## Conditional Control of `datetime` Index in `xarray`\n", "\n", "In Unit 3, we demonstrated how to use the `sel` method with `slice` to select data with a continuous temporal or spatial range. However, sometimes we need to select non-continuous time periods, such as certain months over several years. In these cases, it is not useful to select with `slice`. Therefore, we can use conditional control arguments to select data that meet the requirements we specify. Specifically, the time coordinate in xarray is a datetime object, which includes datetime attributes such as year, month, day, and so on. We can use these attributes to select the dates we like. \n", "\n", "**Example 1: Select only the JAS season data.** " ] }, { "cell_type": "code", "execution_count": 1, "id": "0721be78", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
<xarray.DataArray 'olr' (time: 2208, lat: 90, lon: 360)> Size: 286MB\n", "[71539200 values with dtype=float32]\n", "Coordinates:\n", " * time (time) datetime64[ns] 18kB 1998-07-01 1998-07-02 ... 2021-09-30\n", " * lon (lon) float32 1kB 0.5 1.5 2.5 3.5 4.5 ... 356.5 357.5 358.5 359.5\n", " * lat (lat) float32 360B -44.5 -43.5 -42.5 -41.5 ... 41.5 42.5 43.5 44.5\n", "Attributes:\n", " standard_name: toa_outgoing_longwave_flux\n", " long_name: NOAA Climate Data Record of Daily Mean Upward Longwave Fl...\n", " units: W m-2\n", " cell_methods: time: mean area: mean
<xarray.DataArray 'olr' (time: 8760, lat: 90, lon: 360)> Size: 1GB\n", "[283824000 values with dtype=float32]\n", "Coordinates:\n", " * time (time) datetime64[ns] 70kB 1998-01-01 1998-01-02 ... 2021-12-31\n", " * lon (lon) float32 1kB 0.5 1.5 2.5 3.5 4.5 ... 356.5 357.5 358.5 359.5\n", " * lat (lat) float32 360B -44.5 -43.5 -42.5 -41.5 ... 41.5 42.5 43.5 44.5\n", "Attributes:\n", " standard_name: toa_outgoing_longwave_flux\n", " long_name: NOAA Climate Data Record of Daily Mean Upward Longwave Fl...\n", " units: W m-2\n", " cell_methods: time: mean area: mean
<xarray.DataArray 'strftime' (time: 8760)> Size: 70kB\n", "array(['Jan 01 98', 'Jan 02 98', 'Jan 03 98', ..., 'Dec 29 21',\n", " 'Dec 30 21', 'Dec 31 21'], dtype=object)\n", "Coordinates:\n", " * time (time) datetime64[ns] 70kB 1998-01-01 1998-01-02 ... 2021-12-31