{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "electrical-giving",
   "metadata": {},
   "source": [
    "# Detailed code run\n",
    "Here is a deep dive in to the `xagg` functionality."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "broken-labor",
   "metadata": {},
   "outputs": [],
   "source": [
    "import xagg as xa\n",
    "import xarray as xr\n",
    "import numpy as np\n",
    "import geopandas as gpd"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "healthy-suicide",
   "metadata": {},
   "source": [
    "## Intro\n",
    "We'll be aggregating a gridded dataset onto a set of shapefiles, using an extra set of weights. Specifically, we'll use:\n",
    "- gridded: month-of-year average temperature projections for the end-of-century from a climate model (CCSM4)\n",
    "- shapefiles: US counties\n",
    "- additional weights: global gridded population density ([GPW](https://sedac.ciesin.columbia.edu/data/collection/gpw-v4), 30 min resolution)\n",
    "\n",
    "This is a setup that you may for example use if projecting the impact of temperature on some human variable (temperature vs. mortality, for example) for which you have data at the US county level. Since your mortality data is likely at the county level, you need to aggregate the gridded climate model output data to counties - i.e., what is the average temperature over each county? This code will calculate which pixels overlap each county - and by how much - allowing an area-averaged value for monthly temperature at the county level. \n",
    "\n",
    "However, you also care about where people live - so you'd like to additionally weight your temperature estimate by a population density dataset. This code easily allows such additional weights. The resultant output is a value of temperature for each month at each county, averaged by both the overlap of individual pixels and the population density in those pixels. (_NB: GPWv4 just averages a political unit's population over a pixel grid, so it might not be the best product in this particular use case, but is used as a sample here_)\n",
    "\n",
    "Let's get started."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "convinced-instruction",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load some climate data as an xarray dataset\n",
    "ds = xr.open_dataset('../../data/climate_data/tas_Amon_CCSM4_rcp85_monthavg_20700101-20991231.nc')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "vocational-toolbox",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load US counties shapefile as a geopandas GeoDataFrame\n",
    "gdf = gpd.read_file('../../data/geo_data/UScounties.shp')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "republican-prague",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load global gridded population data from GPW\n",
    "ds_pop = xr.open_dataset('../../data/pop_data/pop2000.nc')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "interstate-yeast",
   "metadata": {},
   "source": [
    "_NB: the GPW file above has been pre-processed, by subsampling to `raster=0` (the 2000 population), and renaming the primary variable to `pop` for ease of use._"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "abandoned-theme",
   "metadata": {},
   "source": [
    "## Calculating area weights between a raster grid and polygons\n",
    "First, `xagg` has to figure out how much each pixel overlaps each polygon. This process requires a few steps:\n",
    "\n",
    "0. Get everything in the right format. \n",
    "    * Gridded data comes in all shapes and sizes. `xagg` is ready to deal with most common grid naming conventions - so no matter if your lat and lon variables are called 'Latitude' and 'Longitude' or 'y' and 'x' or many options in between, as long as they're in xarray Datasets or DataArrays, they'll work. \n",
    "    * Behind the scenes, longitude values are also forced to -180:180 (from 0:360, if applicable), just to make sure everything is operating in the same coordinate system. \n",
    "1. Build polygons for each pixel \n",
    "    * To figure out how much each pixel overlaps each polygon, pixel polygons have to be constructed. If your gridded variable already has \"lat_bnds\" and \"lon_bnds\" (giving the vertices of each pixel) explicitly included in the `xr.Dataset`, then those are used. If none are found, \"lat_bnds\" and \"lon_bnds\" are constructed by assuming the vertices are halfway between the coordinates in degrees. \n",
    "    * If an additional weighting is used, the weighting dataset and your gridded data have to be homogenized at this stage. By default, the weighting dataset is regridded to your gridded data using `xesmf`. Future versions will also allow regridding the gridded data to the weighting dataset here(it's already accounted for in some of the functions, but not all).\n",
    "    * To avoid creating gigantic geodataframes with pixel polygons, the dataset is by default subset to a bounding box around the shapefiles first. In the aggregating code below, this subsetting is taken into account, and the input `ds` into `xa.aggregate` is matched to the original source grid on which the overlaps were calculated. \n",
    "2. Calculate area overlaps between each pixel and each polygon\n",
    "    * Now, the overlap between each pixel and each polygon is calculated. Using `geopandas`' excellent polygon boolean operations and area calculations, the intersection between the raster grid and the polygon is calculated. For each polygon, the coordinates of each pixel that intersects it is saved, as is the relative area of that overlap (as an example, if you had a county the size and shape of one pixel, but located half in one pixel and half in the other pixel, those two pixels would be saved, and their relative area would be 0.5 each). Areas are calculated using the WGS84 geoid. \n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "underlying-utilization",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "creating polygons for each pixel...\n",
      "regridding weights to data grid...\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/kevinschwarzwald/opt/anaconda3/envs/test/lib/python3.9/site-packages/xarray/core/dataarray.py:746: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison\n",
      "  return key in self.data\n",
      "/Users/kevinschwarzwald/opt/anaconda3/envs/test/lib/python3.9/site-packages/xesmf/frontend.py:466: FutureWarning: ``output_sizes`` should be given in the ``dask_gufunc_kwargs`` parameter. It will be removed as direct parameter in a future version.\n",
      "  dr_out = xr.apply_ufunc(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "calculating overlaps between pixels and output polygons...\n",
      "success!\n"
     ]
    }
   ],
   "source": [
    "# Calculate overlaps\n",
    "weightmap = xa.pixel_overlaps(ds,gdf,weights=ds_pop.pop)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "automated-version",
   "metadata": {},
   "source": [
    "## Aggregating gridded data to the polygons using the area weights (and other weights) calculated above\n",
    "Now that we know which pixels overlap which polygons and by how much (and what the value of the population weight for each pixel is), it's time to aggregate data to the polygon level. `xagg` will assume that all variables in the original `ds` that have `lat` and `lon` coordinates should be aggregated. These variables may have extra dimensions (3-D variables (i.e. `lon x lat x time`) are supported; 4-D etc. _should_ be supported but haven't been tested yet - the biggest issue may be in exporting). \n",
    "\n",
    "Since we included an additional weighting grid, this dataset is included in `weightmap` from above and is seamlessly integrated into the weighting scheme.  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "proved-administration",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "adjusting grid... (this may happen because only a subset of pixels were used for aggregation for efficiency - i.e. [subset_bbox=True] in xa.pixel_overlaps())\n",
      "grid adjustment successful\n",
      "aggregating tas...\n",
      "all variables aggregated to polygons!\n"
     ]
    }
   ],
   "source": [
    "# Aggregate\n",
    "aggregated = xa.aggregate(ds,weightmap)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "distinguished-bolivia",
   "metadata": {},
   "source": [
    "## Converting aggregated data\n",
    "Now that the data is aggregated, we want it in a useable format. \n",
    "\n",
    "Supported formats for converting include:\n",
    "- `xarray` Dataset (using `.to_dataset()`)\n",
    "    - Grid dimensions from the original dataset are replaced with a single dimensions for polygons - by default called \"poly_idx\" (change this with the `loc_dim=...` option). Aggregated variables keep their non-grid dimensions unchanged; with their grid dimension replaced as above. \n",
    "    - All original fields from the `geodataframe` are kept as `poly_idx x 1` variables. \n",
    "- `pandas` Dataframe (using `.to_dataframe()`)\n",
    "    - All original fields from the `geodataframe` are kept; the aggregated variables are added as separate columns. If the aggregated variables have a 3rd dimension, they are reshaped long - with procedurally generated column names (just `[var]0`, `[var]1`, ... for now). \n",
    "\n",
    "(the \"raw\" form of the geodataframe used to create these can also be directly accessed through `aggregated.agg`)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "dressed-curve",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div><svg style=\"position: absolute; width: 0; height: 0; overflow: hidden\">\n",
       "<defs>\n",
       "<symbol id=\"icon-database\" viewBox=\"0 0 32 32\">\n",
       "<path d=\"M16 0c-8.837 0-16 2.239-16 5v4c0 2.761 7.163 5 16 5s16-2.239 16-5v-4c0-2.761-7.163-5-16-5z\"></path>\n",
       "<path d=\"M16 17c-8.837 0-16-2.239-16-5v6c0 2.761 7.163 5 16 5s16-2.239 16-5v-6c0 2.761-7.163 5-16 5z\"></path>\n",
       "<path d=\"M16 26c-8.837 0-16-2.239-16-5v6c0 2.761 7.163 5 16 5s16-2.239 16-5v-6c0 2.761-7.163 5-16 5z\"></path>\n",
       "</symbol>\n",
       "<symbol id=\"icon-file-text2\" viewBox=\"0 0 32 32\">\n",
       "<path d=\"M28.681 7.159c-0.694-0.947-1.662-2.053-2.724-3.116s-2.169-2.030-3.116-2.724c-1.612-1.182-2.393-1.319-2.841-1.319h-15.5c-1.378 0-2.5 1.121-2.5 2.5v27c0 1.378 1.122 2.5 2.5 2.5h23c1.378 0 2.5-1.122 2.5-2.5v-19.5c0-0.448-0.137-1.23-1.319-2.841zM24.543 5.457c0.959 0.959 1.712 1.825 2.268 2.543h-4.811v-4.811c0.718 0.556 1.584 1.309 2.543 2.268zM28 29.5c0 0.271-0.229 0.5-0.5 0.5h-23c-0.271 0-0.5-0.229-0.5-0.5v-27c0-0.271 0.229-0.5 0.5-0.5 0 0 15.499-0 15.5 0v7c0 0.552 0.448 1 1 1h7v19.5z\"></path>\n",
       "<path d=\"M23 26h-14c-0.552 0-1-0.448-1-1s0.448-1 1-1h14c0.552 0 1 0.448 1 1s-0.448 1-1 1z\"></path>\n",
       "<path d=\"M23 22h-14c-0.552 0-1-0.448-1-1s0.448-1 1-1h14c0.552 0 1 0.448 1 1s-0.448 1-1 1z\"></path>\n",
       "<path d=\"M23 18h-14c-0.552 0-1-0.448-1-1s0.448-1 1-1h14c0.552 0 1 0.448 1 1s-0.448 1-1 1z\"></path>\n",
       "</symbol>\n",
       "</defs>\n",
       "</svg>\n",
       "<style>/* CSS stylesheet for displaying xarray objects in jupyterlab.\n",
       " *\n",
       " */\n",
       "\n",
       ":root {\n",
       "  --xr-font-color0: var(--jp-content-font-color0, rgba(0, 0, 0, 1));\n",
       "  --xr-font-color2: var(--jp-content-font-color2, rgba(0, 0, 0, 0.54));\n",
       "  --xr-font-color3: var(--jp-content-font-color3, rgba(0, 0, 0, 0.38));\n",
       "  --xr-border-color: var(--jp-border-color2, #e0e0e0);\n",
       "  --xr-disabled-color: var(--jp-layout-color3, #bdbdbd);\n",
       "  --xr-background-color: var(--jp-layout-color0, white);\n",
       "  --xr-background-color-row-even: var(--jp-layout-color1, white);\n",
       "  --xr-background-color-row-odd: var(--jp-layout-color2, #eeeeee);\n",
       "}\n",
       "\n",
       "html[theme=dark],\n",
       "body.vscode-dark {\n",
       "  --xr-font-color0: rgba(255, 255, 255, 1);\n",
       "  --xr-font-color2: rgba(255, 255, 255, 0.54);\n",
       "  --xr-font-color3: rgba(255, 255, 255, 0.38);\n",
       "  --xr-border-color: #1F1F1F;\n",
       "  --xr-disabled-color: #515151;\n",
       "  --xr-background-color: #111111;\n",
       "  --xr-background-color-row-even: #111111;\n",
       "  --xr-background-color-row-odd: #313131;\n",
       "}\n",
       "\n",
       ".xr-wrap {\n",
       "  display: block;\n",
       "  min-width: 300px;\n",
       "  max-width: 700px;\n",
       "}\n",
       "\n",
       ".xr-text-repr-fallback {\n",
       "  /* fallback to plain text repr when CSS is not injected (untrusted notebook) */\n",
       "  display: none;\n",
       "}\n",
       "\n",
       ".xr-header {\n",
       "  padding-top: 6px;\n",
       "  padding-bottom: 6px;\n",
       "  margin-bottom: 4px;\n",
       "  border-bottom: solid 1px var(--xr-border-color);\n",
       "}\n",
       "\n",
       ".xr-header > div,\n",
       ".xr-header > ul {\n",
       "  display: inline;\n",
       "  margin-top: 0;\n",
       "  margin-bottom: 0;\n",
       "}\n",
       "\n",
       ".xr-obj-type,\n",
       ".xr-array-name {\n",
       "  margin-left: 2px;\n",
       "  margin-right: 10px;\n",
       "}\n",
       "\n",
       ".xr-obj-type {\n",
       "  color: var(--xr-font-color2);\n",
       "}\n",
       "\n",
       ".xr-sections {\n",
       "  padding-left: 0 !important;\n",
       "  display: grid;\n",
       "  grid-template-columns: 150px auto auto 1fr 20px 20px;\n",
       "}\n",
       "\n",
       ".xr-section-item {\n",
       "  display: contents;\n",
       "}\n",
       "\n",
       ".xr-section-item input {\n",
       "  display: none;\n",
       "}\n",
       "\n",
       ".xr-section-item input + label {\n",
       "  color: var(--xr-disabled-color);\n",
       "}\n",
       "\n",
       ".xr-section-item input:enabled + label {\n",
       "  cursor: pointer;\n",
       "  color: var(--xr-font-color2);\n",
       "}\n",
       "\n",
       ".xr-section-item input:enabled + label:hover {\n",
       "  color: var(--xr-font-color0);\n",
       "}\n",
       "\n",
       ".xr-section-summary {\n",
       "  grid-column: 1;\n",
       "  color: var(--xr-font-color2);\n",
       "  font-weight: 500;\n",
       "}\n",
       "\n",
       ".xr-section-summary > span {\n",
       "  display: inline-block;\n",
       "  padding-left: 0.5em;\n",
       "}\n",
       "\n",
       ".xr-section-summary-in:disabled + label {\n",
       "  color: var(--xr-font-color2);\n",
       "}\n",
       "\n",
       ".xr-section-summary-in + label:before {\n",
       "  display: inline-block;\n",
       "  content: '►';\n",
       "  font-size: 11px;\n",
       "  width: 15px;\n",
       "  text-align: center;\n",
       "}\n",
       "\n",
       ".xr-section-summary-in:disabled + label:before {\n",
       "  color: var(--xr-disabled-color);\n",
       "}\n",
       "\n",
       ".xr-section-summary-in:checked + label:before {\n",
       "  content: '▼';\n",
       "}\n",
       "\n",
       ".xr-section-summary-in:checked + label > span {\n",
       "  display: none;\n",
       "}\n",
       "\n",
       ".xr-section-summary,\n",
       ".xr-section-inline-details {\n",
       "  padding-top: 4px;\n",
       "  padding-bottom: 4px;\n",
       "}\n",
       "\n",
       ".xr-section-inline-details {\n",
       "  grid-column: 2 / -1;\n",
       "}\n",
       "\n",
       ".xr-section-details {\n",
       "  display: none;\n",
       "  grid-column: 1 / -1;\n",
       "  margin-bottom: 5px;\n",
       "}\n",
       "\n",
       ".xr-section-summary-in:checked ~ .xr-section-details {\n",
       "  display: contents;\n",
       "}\n",
       "\n",
       ".xr-array-wrap {\n",
       "  grid-column: 1 / -1;\n",
       "  display: grid;\n",
       "  grid-template-columns: 20px auto;\n",
       "}\n",
       "\n",
       ".xr-array-wrap > label {\n",
       "  grid-column: 1;\n",
       "  vertical-align: top;\n",
       "}\n",
       "\n",
       ".xr-preview {\n",
       "  color: var(--xr-font-color3);\n",
       "}\n",
       "\n",
       ".xr-array-preview,\n",
       ".xr-array-data {\n",
       "  padding: 0 5px !important;\n",
       "  grid-column: 2;\n",
       "}\n",
       "\n",
       ".xr-array-data,\n",
       ".xr-array-in:checked ~ .xr-array-preview {\n",
       "  display: none;\n",
       "}\n",
       "\n",
       ".xr-array-in:checked ~ .xr-array-data,\n",
       ".xr-array-preview {\n",
       "  display: inline-block;\n",
       "}\n",
       "\n",
       ".xr-dim-list {\n",
       "  display: inline-block !important;\n",
       "  list-style: none;\n",
       "  padding: 0 !important;\n",
       "  margin: 0;\n",
       "}\n",
       "\n",
       ".xr-dim-list li {\n",
       "  display: inline-block;\n",
       "  padding: 0;\n",
       "  margin: 0;\n",
       "}\n",
       "\n",
       ".xr-dim-list:before {\n",
       "  content: '(';\n",
       "}\n",
       "\n",
       ".xr-dim-list:after {\n",
       "  content: ')';\n",
       "}\n",
       "\n",
       ".xr-dim-list li:not(:last-child):after {\n",
       "  content: ',';\n",
       "  padding-right: 5px;\n",
       "}\n",
       "\n",
       ".xr-has-index {\n",
       "  font-weight: bold;\n",
       "}\n",
       "\n",
       ".xr-var-list,\n",
       ".xr-var-item {\n",
       "  display: contents;\n",
       "}\n",
       "\n",
       ".xr-var-item > div,\n",
       ".xr-var-item label,\n",
       ".xr-var-item > .xr-var-name span {\n",
       "  background-color: var(--xr-background-color-row-even);\n",
       "  margin-bottom: 0;\n",
       "}\n",
       "\n",
       ".xr-var-item > .xr-var-name:hover span {\n",
       "  padding-right: 5px;\n",
       "}\n",
       "\n",
       ".xr-var-list > li:nth-child(odd) > div,\n",
       ".xr-var-list > li:nth-child(odd) > label,\n",
       ".xr-var-list > li:nth-child(odd) > .xr-var-name span {\n",
       "  background-color: var(--xr-background-color-row-odd);\n",
       "}\n",
       "\n",
       ".xr-var-name {\n",
       "  grid-column: 1;\n",
       "}\n",
       "\n",
       ".xr-var-dims {\n",
       "  grid-column: 2;\n",
       "}\n",
       "\n",
       ".xr-var-dtype {\n",
       "  grid-column: 3;\n",
       "  text-align: right;\n",
       "  color: var(--xr-font-color2);\n",
       "}\n",
       "\n",
       ".xr-var-preview {\n",
       "  grid-column: 4;\n",
       "}\n",
       "\n",
       ".xr-var-name,\n",
       ".xr-var-dims,\n",
       ".xr-var-dtype,\n",
       ".xr-preview,\n",
       ".xr-attrs dt {\n",
       "  white-space: nowrap;\n",
       "  overflow: hidden;\n",
       "  text-overflow: ellipsis;\n",
       "  padding-right: 10px;\n",
       "}\n",
       "\n",
       ".xr-var-name:hover,\n",
       ".xr-var-dims:hover,\n",
       ".xr-var-dtype:hover,\n",
       ".xr-attrs dt:hover {\n",
       "  overflow: visible;\n",
       "  width: auto;\n",
       "  z-index: 1;\n",
       "}\n",
       "\n",
       ".xr-var-attrs,\n",
       ".xr-var-data {\n",
       "  display: none;\n",
       "  background-color: var(--xr-background-color) !important;\n",
       "  padding-bottom: 5px !important;\n",
       "}\n",
       "\n",
       ".xr-var-attrs-in:checked ~ .xr-var-attrs,\n",
       ".xr-var-data-in:checked ~ .xr-var-data {\n",
       "  display: block;\n",
       "}\n",
       "\n",
       ".xr-var-data > table {\n",
       "  float: right;\n",
       "}\n",
       "\n",
       ".xr-var-name span,\n",
       ".xr-var-data,\n",
       ".xr-attrs {\n",
       "  padding-left: 25px !important;\n",
       "}\n",
       "\n",
       ".xr-attrs,\n",
       ".xr-var-attrs,\n",
       ".xr-var-data {\n",
       "  grid-column: 1 / -1;\n",
       "}\n",
       "\n",
       "dl.xr-attrs {\n",
       "  padding: 0;\n",
       "  margin: 0;\n",
       "  display: grid;\n",
       "  grid-template-columns: 125px auto;\n",
       "}\n",
       "\n",
       ".xr-attrs dt,\n",
       ".xr-attrs dd {\n",
       "  padding: 0;\n",
       "  margin: 0;\n",
       "  float: left;\n",
       "  padding-right: 10px;\n",
       "  width: auto;\n",
       "}\n",
       "\n",
       ".xr-attrs dt {\n",
       "  font-weight: normal;\n",
       "  grid-column: 1;\n",
       "}\n",
       "\n",
       ".xr-attrs dt:hover span {\n",
       "  display: inline-block;\n",
       "  background: var(--xr-background-color);\n",
       "  padding-right: 10px;\n",
       "}\n",
       "\n",
       ".xr-attrs dd {\n",
       "  grid-column: 2;\n",
       "  white-space: pre-wrap;\n",
       "  word-break: break-all;\n",
       "}\n",
       "\n",
       ".xr-icon-database,\n",
       ".xr-icon-file-text2 {\n",
       "  display: inline-block;\n",
       "  vertical-align: middle;\n",
       "  width: 1em;\n",
       "  height: 1.5em !important;\n",
       "  stroke-width: 0;\n",
       "  stroke: currentColor;\n",
       "  fill: currentColor;\n",
       "}\n",
       "</style><pre class='xr-text-repr-fallback'>&lt;xarray.Dataset&gt;\n",
       "Dimensions:     (month: 12, pix_idx: 3141)\n",
       "Coordinates:\n",
       "  * pix_idx     (pix_idx) int64 0 1 2 3 4 5 6 ... 3135 3136 3137 3138 3139 3140\n",
       "  * month       (month) int64 1 2 3 4 5 6 7 8 9 10 11 12\n",
       "Data variables:\n",
       "    NAME        (pix_idx) object &#x27;Lake of the Woods&#x27; &#x27;Ferry&#x27; ... &#x27;Broomfield&#x27;\n",
       "    STATE_NAME  (pix_idx) object &#x27;Minnesota&#x27; &#x27;Washington&#x27; ... &#x27;Colorado&#x27;\n",
       "    STATE_FIPS  (pix_idx) object &#x27;27&#x27; &#x27;53&#x27; &#x27;53&#x27; &#x27;53&#x27; ... &#x27;02&#x27; &#x27;02&#x27; &#x27;02&#x27; &#x27;08&#x27;\n",
       "    CNTY_FIPS   (pix_idx) object &#x27;077&#x27; &#x27;019&#x27; &#x27;065&#x27; &#x27;047&#x27; ... &#x27;240&#x27; &#x27;068&#x27; &#x27;014&#x27;\n",
       "    FIPS        (pix_idx) object &#x27;27077&#x27; &#x27;53019&#x27; &#x27;53065&#x27; ... &#x27;02068&#x27; &#x27;08014&#x27;\n",
       "    tas         (pix_idx, month) float64 264.0 268.9 274.0 ... 283.5 276.4 270.4</pre><div class='xr-wrap' hidden><div class='xr-header'><div class='xr-obj-type'>xarray.Dataset</div></div><ul class='xr-sections'><li class='xr-section-item'><input id='section-61bbd9cd-6f0c-4594-bb01-037ef123d15c' class='xr-section-summary-in' type='checkbox' disabled ><label for='section-61bbd9cd-6f0c-4594-bb01-037ef123d15c' class='xr-section-summary'  title='Expand/collapse section'>Dimensions:</label><div class='xr-section-inline-details'><ul class='xr-dim-list'><li><span class='xr-has-index'>month</span>: 12</li><li><span class='xr-has-index'>pix_idx</span>: 3141</li></ul></div><div class='xr-section-details'></div></li><li class='xr-section-item'><input id='section-6e0a2ea6-4710-48d9-b953-a05a28cdadb5' class='xr-section-summary-in' type='checkbox'  checked><label for='section-6e0a2ea6-4710-48d9-b953-a05a28cdadb5' class='xr-section-summary' >Coordinates: <span>(2)</span></label><div class='xr-section-inline-details'></div><div class='xr-section-details'><ul class='xr-var-list'><li class='xr-var-item'><div class='xr-var-name'><span class='xr-has-index'>pix_idx</span></div><div class='xr-var-dims'>(pix_idx)</div><div class='xr-var-dtype'>int64</div><div class='xr-var-preview xr-preview'>0 1 2 3 4 ... 3137 3138 3139 3140</div><input id='attrs-4d2bb7c0-ad03-47c3-a77c-4e127f6a3980' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-4d2bb7c0-ad03-47c3-a77c-4e127f6a3980' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-94142a70-8981-43f2-9f77-576947cd1c36' class='xr-var-data-in' type='checkbox'><label for='data-94142a70-8981-43f2-9f77-576947cd1c36' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array([   0,    1,    2, ..., 3138, 3139, 3140])</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span class='xr-has-index'>month</span></div><div class='xr-var-dims'>(month)</div><div class='xr-var-dtype'>int64</div><div class='xr-var-preview xr-preview'>1 2 3 4 5 6 7 8 9 10 11 12</div><input id='attrs-5f9c5863-be53-4362-b177-448b403f2706' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-5f9c5863-be53-4362-b177-448b403f2706' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-7a56bf74-9ee2-4db8-8e38-def1602167d6' class='xr-var-data-in' type='checkbox'><label for='data-7a56bf74-9ee2-4db8-8e38-def1602167d6' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12])</pre></div></li></ul></div></li><li class='xr-section-item'><input id='section-c989583b-6e96-487d-bd9b-3451238cbc26' class='xr-section-summary-in' type='checkbox'  checked><label for='section-c989583b-6e96-487d-bd9b-3451238cbc26' class='xr-section-summary' >Data variables: <span>(6)</span></label><div class='xr-section-inline-details'></div><div class='xr-section-details'><ul class='xr-var-list'><li class='xr-var-item'><div class='xr-var-name'><span>NAME</span></div><div class='xr-var-dims'>(pix_idx)</div><div class='xr-var-dtype'>object</div><div class='xr-var-preview xr-preview'>&#x27;Lake of the Woods&#x27; ... &#x27;Broomfi...</div><input id='attrs-66252898-8590-4be3-b178-752dba91618a' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-66252898-8590-4be3-b178-752dba91618a' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-c748084f-0936-452c-b971-b9912ffd315d' class='xr-var-data-in' type='checkbox'><label for='data-c748084f-0936-452c-b971-b9912ffd315d' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array([&#x27;Lake of the Woods&#x27;, &#x27;Ferry&#x27;, &#x27;Stevens&#x27;, ...,\n",
       "       &#x27;Southeast Fairbanks&#x27;, &#x27;Denali&#x27;, &#x27;Broomfield&#x27;], dtype=object)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>STATE_NAME</span></div><div class='xr-var-dims'>(pix_idx)</div><div class='xr-var-dtype'>object</div><div class='xr-var-preview xr-preview'>&#x27;Minnesota&#x27; ... &#x27;Colorado&#x27;</div><input id='attrs-ae5f1bb7-b967-4ea2-8933-e4e9977c528f' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-ae5f1bb7-b967-4ea2-8933-e4e9977c528f' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-6f4f0db2-6418-4668-b815-fe77a9ec58a8' class='xr-var-data-in' type='checkbox'><label for='data-6f4f0db2-6418-4668-b815-fe77a9ec58a8' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array([&#x27;Minnesota&#x27;, &#x27;Washington&#x27;, &#x27;Washington&#x27;, ..., &#x27;Alaska&#x27;, &#x27;Alaska&#x27;,\n",
       "       &#x27;Colorado&#x27;], dtype=object)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>STATE_FIPS</span></div><div class='xr-var-dims'>(pix_idx)</div><div class='xr-var-dtype'>object</div><div class='xr-var-preview xr-preview'>&#x27;27&#x27; &#x27;53&#x27; &#x27;53&#x27; ... &#x27;02&#x27; &#x27;02&#x27; &#x27;08&#x27;</div><input id='attrs-4210d0c7-a77c-46b4-ab36-e86d00a51b68' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-4210d0c7-a77c-46b4-ab36-e86d00a51b68' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-2ad423d7-4484-4cf7-aeeb-ae96750d7014' class='xr-var-data-in' type='checkbox'><label for='data-2ad423d7-4484-4cf7-aeeb-ae96750d7014' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array([&#x27;27&#x27;, &#x27;53&#x27;, &#x27;53&#x27;, ..., &#x27;02&#x27;, &#x27;02&#x27;, &#x27;08&#x27;], dtype=object)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>CNTY_FIPS</span></div><div class='xr-var-dims'>(pix_idx)</div><div class='xr-var-dtype'>object</div><div class='xr-var-preview xr-preview'>&#x27;077&#x27; &#x27;019&#x27; &#x27;065&#x27; ... &#x27;068&#x27; &#x27;014&#x27;</div><input id='attrs-1c2f2ad5-c0b6-4fa5-aa56-59d40b66aebd' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-1c2f2ad5-c0b6-4fa5-aa56-59d40b66aebd' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-322a4c28-93e8-474f-9847-93264bfd99c1' class='xr-var-data-in' type='checkbox'><label for='data-322a4c28-93e8-474f-9847-93264bfd99c1' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array([&#x27;077&#x27;, &#x27;019&#x27;, &#x27;065&#x27;, ..., &#x27;240&#x27;, &#x27;068&#x27;, &#x27;014&#x27;], dtype=object)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>FIPS</span></div><div class='xr-var-dims'>(pix_idx)</div><div class='xr-var-dtype'>object</div><div class='xr-var-preview xr-preview'>&#x27;27077&#x27; &#x27;53019&#x27; ... &#x27;02068&#x27; &#x27;08014&#x27;</div><input id='attrs-55d940a9-a3c2-4167-87e8-c16603a3a61f' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-55d940a9-a3c2-4167-87e8-c16603a3a61f' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-2d6778ad-5dd1-4537-bd20-f96364cfa35e' class='xr-var-data-in' type='checkbox'><label for='data-2d6778ad-5dd1-4537-bd20-f96364cfa35e' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array([&#x27;27077&#x27;, &#x27;53019&#x27;, &#x27;53065&#x27;, ..., &#x27;02240&#x27;, &#x27;02068&#x27;, &#x27;08014&#x27;],\n",
       "      dtype=object)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>tas</span></div><div class='xr-var-dims'>(pix_idx, month)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>264.0 268.9 274.0 ... 276.4 270.4</div><input id='attrs-2cc0790b-1fda-492b-972c-0a1e5f6d59df' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-2cc0790b-1fda-492b-972c-0a1e5f6d59df' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-0e2232d4-95a5-46a0-a2a2-4330b086a917' class='xr-var-data-in' type='checkbox'><label for='data-0e2232d4-95a5-46a0-a2a2-4330b086a917' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array([[263.9780062 , 268.88786769, 274.01215237, ..., 283.81523287,\n",
       "        275.1416336 , 266.05442984],\n",
       "       [271.78043992, 275.61848506, 276.93418312, ..., 281.63345613,\n",
       "        276.71447491, 272.24200396],\n",
       "       [273.2172504 , 276.94037995, 278.41422511, ..., 283.27395604,\n",
       "        278.0632773 , 273.66618058],\n",
       "       ...,\n",
       "       [263.91916835, 263.8990788 , 266.77151431, ..., 272.37796292,\n",
       "        265.7020255 , 264.41430223],\n",
       "       [265.04959892, 264.79484859, 268.19315553, ..., 273.14260516,\n",
       "        266.53491609, 265.57515291],\n",
       "       [270.80386353, 273.4302063 , 275.95550537, ..., 283.54470825,\n",
       "        276.38360596, 270.44485474]])</pre></div></li></ul></div></li><li class='xr-section-item'><input id='section-c1f54a35-eca3-4519-afc0-89fb25925e38' class='xr-section-summary-in' type='checkbox' disabled ><label for='section-c1f54a35-eca3-4519-afc0-89fb25925e38' class='xr-section-summary'  title='Expand/collapse section'>Attributes: <span>(0)</span></label><div class='xr-section-inline-details'></div><div class='xr-section-details'><dl class='xr-attrs'></dl></div></li></ul></div></div>"
      ],
      "text/plain": [
       "<xarray.Dataset>\n",
       "Dimensions:     (month: 12, pix_idx: 3141)\n",
       "Coordinates:\n",
       "  * pix_idx     (pix_idx) int64 0 1 2 3 4 5 6 ... 3135 3136 3137 3138 3139 3140\n",
       "  * month       (month) int64 1 2 3 4 5 6 7 8 9 10 11 12\n",
       "Data variables:\n",
       "    NAME        (pix_idx) object 'Lake of the Woods' 'Ferry' ... 'Broomfield'\n",
       "    STATE_NAME  (pix_idx) object 'Minnesota' 'Washington' ... 'Colorado'\n",
       "    STATE_FIPS  (pix_idx) object '27' '53' '53' '53' ... '02' '02' '02' '08'\n",
       "    CNTY_FIPS   (pix_idx) object '077' '019' '065' '047' ... '240' '068' '014'\n",
       "    FIPS        (pix_idx) object '27077' '53019' '53065' ... '02068' '08014'\n",
       "    tas         (pix_idx, month) float64 264.0 268.9 274.0 ... 283.5 276.4 270.4"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Example as a dataset\n",
    "ds_out = aggregated.to_dataset()\n",
    "ds_out"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "electrical-ticket",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>NAME</th>\n",
       "      <th>STATE_NAME</th>\n",
       "      <th>STATE_FIPS</th>\n",
       "      <th>CNTY_FIPS</th>\n",
       "      <th>FIPS</th>\n",
       "      <th>tas0</th>\n",
       "      <th>tas1</th>\n",
       "      <th>tas2</th>\n",
       "      <th>tas3</th>\n",
       "      <th>tas4</th>\n",
       "      <th>tas5</th>\n",
       "      <th>tas6</th>\n",
       "      <th>tas7</th>\n",
       "      <th>tas8</th>\n",
       "      <th>tas9</th>\n",
       "      <th>tas10</th>\n",
       "      <th>tas11</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Lake of the Woods</td>\n",
       "      <td>Minnesota</td>\n",
       "      <td>27</td>\n",
       "      <td>077</td>\n",
       "      <td>27077</td>\n",
       "      <td>263.978006</td>\n",
       "      <td>268.887868</td>\n",
       "      <td>274.012152</td>\n",
       "      <td>283.158717</td>\n",
       "      <td>290.630598</td>\n",
       "      <td>297.850779</td>\n",
       "      <td>302.038199</td>\n",
       "      <td>300.327744</td>\n",
       "      <td>293.465816</td>\n",
       "      <td>283.815233</td>\n",
       "      <td>275.141634</td>\n",
       "      <td>266.054430</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>Ferry</td>\n",
       "      <td>Washington</td>\n",
       "      <td>53</td>\n",
       "      <td>019</td>\n",
       "      <td>53019</td>\n",
       "      <td>271.780440</td>\n",
       "      <td>275.618485</td>\n",
       "      <td>276.934183</td>\n",
       "      <td>279.826777</td>\n",
       "      <td>286.621100</td>\n",
       "      <td>293.757010</td>\n",
       "      <td>299.056368</td>\n",
       "      <td>297.131708</td>\n",
       "      <td>289.844308</td>\n",
       "      <td>281.633456</td>\n",
       "      <td>276.714475</td>\n",
       "      <td>272.242004</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Stevens</td>\n",
       "      <td>Washington</td>\n",
       "      <td>53</td>\n",
       "      <td>065</td>\n",
       "      <td>53065</td>\n",
       "      <td>273.217250</td>\n",
       "      <td>276.940380</td>\n",
       "      <td>278.414225</td>\n",
       "      <td>281.319652</td>\n",
       "      <td>287.817911</td>\n",
       "      <td>294.926457</td>\n",
       "      <td>300.903109</td>\n",
       "      <td>299.304529</td>\n",
       "      <td>292.245363</td>\n",
       "      <td>283.273956</td>\n",
       "      <td>278.063277</td>\n",
       "      <td>273.666181</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>Okanogan</td>\n",
       "      <td>Washington</td>\n",
       "      <td>53</td>\n",
       "      <td>047</td>\n",
       "      <td>53047</td>\n",
       "      <td>271.831071</td>\n",
       "      <td>275.586124</td>\n",
       "      <td>276.689357</td>\n",
       "      <td>279.324166</td>\n",
       "      <td>285.771338</td>\n",
       "      <td>292.635899</td>\n",
       "      <td>297.756402</td>\n",
       "      <td>295.956748</td>\n",
       "      <td>289.177685</td>\n",
       "      <td>281.440422</td>\n",
       "      <td>276.654779</td>\n",
       "      <td>272.275232</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>Pend Oreille</td>\n",
       "      <td>Washington</td>\n",
       "      <td>53</td>\n",
       "      <td>051</td>\n",
       "      <td>53051</td>\n",
       "      <td>272.092353</td>\n",
       "      <td>275.888818</td>\n",
       "      <td>277.346070</td>\n",
       "      <td>280.446389</td>\n",
       "      <td>287.268406</td>\n",
       "      <td>294.357705</td>\n",
       "      <td>299.851527</td>\n",
       "      <td>297.965815</td>\n",
       "      <td>290.622763</td>\n",
       "      <td>282.058301</td>\n",
       "      <td>276.996473</td>\n",
       "      <td>272.484589</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3136</th>\n",
       "      <td>Skagway-Hoonah-Angoon</td>\n",
       "      <td>Alaska</td>\n",
       "      <td>02</td>\n",
       "      <td>232</td>\n",
       "      <td>02232</td>\n",
       "      <td>273.605147</td>\n",
       "      <td>275.477240</td>\n",
       "      <td>276.792992</td>\n",
       "      <td>279.194054</td>\n",
       "      <td>283.764519</td>\n",
       "      <td>288.635583</td>\n",
       "      <td>290.038044</td>\n",
       "      <td>289.689574</td>\n",
       "      <td>286.058608</td>\n",
       "      <td>280.958010</td>\n",
       "      <td>276.904109</td>\n",
       "      <td>274.048888</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3137</th>\n",
       "      <td>Yukon-Koyukuk</td>\n",
       "      <td>Alaska</td>\n",
       "      <td>02</td>\n",
       "      <td>290</td>\n",
       "      <td>02290</td>\n",
       "      <td>264.534558</td>\n",
       "      <td>264.088869</td>\n",
       "      <td>267.621423</td>\n",
       "      <td>273.426228</td>\n",
       "      <td>281.649435</td>\n",
       "      <td>289.319370</td>\n",
       "      <td>288.936030</td>\n",
       "      <td>286.209616</td>\n",
       "      <td>280.807791</td>\n",
       "      <td>273.683875</td>\n",
       "      <td>266.722855</td>\n",
       "      <td>265.538685</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3138</th>\n",
       "      <td>Southeast Fairbanks</td>\n",
       "      <td>Alaska</td>\n",
       "      <td>02</td>\n",
       "      <td>240</td>\n",
       "      <td>02240</td>\n",
       "      <td>263.919168</td>\n",
       "      <td>263.899079</td>\n",
       "      <td>266.771514</td>\n",
       "      <td>272.144709</td>\n",
       "      <td>279.739283</td>\n",
       "      <td>287.625174</td>\n",
       "      <td>287.933732</td>\n",
       "      <td>285.436821</td>\n",
       "      <td>279.768225</td>\n",
       "      <td>272.377963</td>\n",
       "      <td>265.702026</td>\n",
       "      <td>264.414302</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3139</th>\n",
       "      <td>Denali</td>\n",
       "      <td>Alaska</td>\n",
       "      <td>02</td>\n",
       "      <td>068</td>\n",
       "      <td>02068</td>\n",
       "      <td>265.049599</td>\n",
       "      <td>264.794849</td>\n",
       "      <td>268.193156</td>\n",
       "      <td>273.612534</td>\n",
       "      <td>281.097223</td>\n",
       "      <td>288.917064</td>\n",
       "      <td>288.898311</td>\n",
       "      <td>286.233612</td>\n",
       "      <td>280.504391</td>\n",
       "      <td>273.142605</td>\n",
       "      <td>266.534916</td>\n",
       "      <td>265.575153</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3140</th>\n",
       "      <td>Broomfield</td>\n",
       "      <td>Colorado</td>\n",
       "      <td>08</td>\n",
       "      <td>014</td>\n",
       "      <td>08014</td>\n",
       "      <td>270.803864</td>\n",
       "      <td>273.430206</td>\n",
       "      <td>275.955505</td>\n",
       "      <td>280.790070</td>\n",
       "      <td>287.303619</td>\n",
       "      <td>292.830048</td>\n",
       "      <td>297.615662</td>\n",
       "      <td>297.646820</td>\n",
       "      <td>292.368988</td>\n",
       "      <td>283.544708</td>\n",
       "      <td>276.383606</td>\n",
       "      <td>270.444855</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>3141 rows × 17 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "                       NAME  STATE_NAME STATE_FIPS CNTY_FIPS   FIPS  \\\n",
       "0         Lake of the Woods   Minnesota         27       077  27077   \n",
       "1                     Ferry  Washington         53       019  53019   \n",
       "2                   Stevens  Washington         53       065  53065   \n",
       "3                  Okanogan  Washington         53       047  53047   \n",
       "4              Pend Oreille  Washington         53       051  53051   \n",
       "...                     ...         ...        ...       ...    ...   \n",
       "3136  Skagway-Hoonah-Angoon      Alaska         02       232  02232   \n",
       "3137          Yukon-Koyukuk      Alaska         02       290  02290   \n",
       "3138    Southeast Fairbanks      Alaska         02       240  02240   \n",
       "3139                 Denali      Alaska         02       068  02068   \n",
       "3140             Broomfield    Colorado         08       014  08014   \n",
       "\n",
       "            tas0        tas1        tas2        tas3        tas4        tas5  \\\n",
       "0     263.978006  268.887868  274.012152  283.158717  290.630598  297.850779   \n",
       "1     271.780440  275.618485  276.934183  279.826777  286.621100  293.757010   \n",
       "2     273.217250  276.940380  278.414225  281.319652  287.817911  294.926457   \n",
       "3     271.831071  275.586124  276.689357  279.324166  285.771338  292.635899   \n",
       "4     272.092353  275.888818  277.346070  280.446389  287.268406  294.357705   \n",
       "...          ...         ...         ...         ...         ...         ...   \n",
       "3136  273.605147  275.477240  276.792992  279.194054  283.764519  288.635583   \n",
       "3137  264.534558  264.088869  267.621423  273.426228  281.649435  289.319370   \n",
       "3138  263.919168  263.899079  266.771514  272.144709  279.739283  287.625174   \n",
       "3139  265.049599  264.794849  268.193156  273.612534  281.097223  288.917064   \n",
       "3140  270.803864  273.430206  275.955505  280.790070  287.303619  292.830048   \n",
       "\n",
       "            tas6        tas7        tas8        tas9       tas10       tas11  \n",
       "0     302.038199  300.327744  293.465816  283.815233  275.141634  266.054430  \n",
       "1     299.056368  297.131708  289.844308  281.633456  276.714475  272.242004  \n",
       "2     300.903109  299.304529  292.245363  283.273956  278.063277  273.666181  \n",
       "3     297.756402  295.956748  289.177685  281.440422  276.654779  272.275232  \n",
       "4     299.851527  297.965815  290.622763  282.058301  276.996473  272.484589  \n",
       "...          ...         ...         ...         ...         ...         ...  \n",
       "3136  290.038044  289.689574  286.058608  280.958010  276.904109  274.048888  \n",
       "3137  288.936030  286.209616  280.807791  273.683875  266.722855  265.538685  \n",
       "3138  287.933732  285.436821  279.768225  272.377963  265.702026  264.414302  \n",
       "3139  288.898311  286.233612  280.504391  273.142605  266.534916  265.575153  \n",
       "3140  297.615662  297.646820  292.368988  283.544708  276.383606  270.444855  \n",
       "\n",
       "[3141 rows x 17 columns]"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Example as a dataframe\n",
    "df_out = aggregated.to_dataframe()\n",
    "df_out"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "likely-grade",
   "metadata": {},
   "source": [
    "## Exporting aggregated data"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "framed-adjustment",
   "metadata": {},
   "source": [
    "For reproducability and code simplicity, you will likely want to save your aggregated data. In addtion, many researchers use multiple languages or software packages as part of their workflow; for example, STATA or R for regression analysis, or QGIS for spatial analysis, and need to be able to transfer their work to these other environments. \n",
    "\n",
    "`xagg` has built-in export functions that allow the export of aggregated data to:\n",
    "- NetCDF\n",
    "- csv (for use in STATA, R)\n",
    "- shapefile (for use in GIS applications)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "pleased-acquisition",
   "metadata": {},
   "source": [
    "### Export to netCDF\n",
    "The netCDF export functionality saves all aggregated variables by replacing the grid dimensions (`lat`, `lon`) with a single location dimension (called `poly_idx`, but this can be changed with the `loc_dim=` argument). \n",
    "\n",
    "Other dimensions (e.g. `time`) are kept as they were originally in the grid variable.\n",
    "\n",
    "Fields in the inputted polygons (e.g., FIPS codes for the US Counties shapefile used here) are saved as additional variables. Attributes from the original `xarray` structure are kept. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "horizontal-reduction",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Export to netcdf\n",
    "aggregated.to_netcdf('file_out.nc')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "selected-tampa",
   "metadata": {},
   "source": [
    "### Export to .csv\n",
    "The .csv output functionality saves files in a polygon (rows) vs. variables (columns) format. Each aggregated variable and each field in the original inputted polygons are saved as columns. Named attributes in the inputted netcdf file are not included. \n",
    "\n",
    "Currently .csvs are only saved \"wide\" - i.e., a `lat x lon x time` variable `tas`, aggregated to `location x time`, would be reshaped wide so that each timestep is saved in its own column, named `tas0`, `tas1`, and so forth. \n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "compact-opera",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Export to csv\n",
    "aggregated.to_csv('file_out.csv')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "checked-bikini",
   "metadata": {},
   "source": [
    "### Export to shapefile\n",
    "The shapefile export functionality keeps the geometry of the originally input polygons, and adds the aggregated variables as fields. \n",
    "\n",
    "Similar to .csv export above, if aggregated variables have a dimension beyond their location dimensions (e.g., `time`), each step in that dimension is saved in a separate field, named after the variable and the integer of the index along that dimension (e.g., `tas0`, `tas1`, etc. for a variable `tas`). \n",
    "\n",
    "Named attributes in the inputted netcdf file are not included. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "serious-placement",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Export to csv\n",
    "aggregated.to_csv('file_out.shp')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
