Skip to content

Commit

Permalink
added nb w-avg
Browse files Browse the repository at this point in the history
  • Loading branch information
cehbrecht committed Sep 27, 2023
1 parent aeb6b1e commit 6c77834
Showing 1 changed file with 114 additions and 0 deletions.
114 changes: 114 additions & 0 deletions notebooks/weighted_average.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "ee398d02-1958-4e73-b9ef-137185bd97d3",
"metadata": {},
"source": [
"# Weighted Average\n",
"\n",
"https://docs.xarray.dev/en/stable/examples/area_weighted_temperature.html"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "037931cd-d112-4460-86a3-848dd28efd6e",
"metadata": {},
"outputs": [],
"source": [
"import xarray as xr\n",
"import pandas as pd\n",
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4e8fdd3b-4943-4d3a-a492-d18e3e686247",
"metadata": {},
"outputs": [],
"source": [
"from pathlib import Path\n",
"data_dir = Path(\"/Users/pingu/tmp\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e0d9a0ba-34d6-4d94-b3a6-9fc5b13eedd8",
"metadata": {},
"outputs": [],
"source": [
"cmip6_files = sorted(data_dir.glob('**/*.nc'))\n",
"cmip6_files"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "60c13c47-e097-4829-a9e7-2de5543476dd",
"metadata": {},
"outputs": [],
"source": [
"ds = xr.open_dataset(cmip6_files[0])\n",
"ds"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "53819d47-53d2-4e77-b020-e91b4cc38fde",
"metadata": {},
"outputs": [],
"source": [
"weights = np.cos(np.deg2rad(ds.lat))\n",
"weights.name = \"weights\"\n",
"weights"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "13097b15-cb02-4577-b4d1-032553a8eff6",
"metadata": {},
"outputs": [],
"source": [
"ds_weighted = ds.weighted(weights)\n",
"ds_weighted"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "444bbc02-d8b5-450f-9e79-f8aac2b64a7e",
"metadata": {},
"outputs": [],
"source": [
"weighted_mean = ds_weighted.mean((\"lon\", \"lat\"))\n",
"weighted_mean"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"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.10.12"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

0 comments on commit 6c77834

Please sign in to comment.