{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Changing units in dataset\n\nThis is an example of how to change\nunits in the xarray dataset.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\nfrom arm_test_data import DATASETS\n\nimport act\n\n\ndef print_summary(ds, variables):\n for var_name in variables:\n print(\n f'{var_name}: mean={np.nanmean(ds[var_name].values)} '\n f\"units={ds[var_name].attrs['units']}\"\n )\n print()\n\n\nvariables = ['first_cbh', 'second_cbh', 'alt']\n\n# Read in some example data\nfilename_ceil = DATASETS.fetch('sgpceilC1.b1.20190101.000000.nc')\nds = act.io.arm.read_arm_netcdf(filename_ceil)\n\n# Print the variable name, mean of values and units\nprint('Variables in read data')\nprint_summary(ds, variables)\n\n# Change units of one varible from m to km\nds.utils.change_units(variables='first_cbh', desired_unit='km')\nprint('Variables with one changed to km')\nprint_summary(ds, variables)\n\n# Change units of more than one varible from to km\nds.utils.change_units(variables=variables, desired_unit='km')\nprint('Variables with both changed to km')\nprint_summary(ds, variables)\n\n# Can change all data variables in the dataset that are units of length by not providing\n# a list of variables. Here we are changing back to orginal meters.\n# Also, because it needs to loop over all variables and try to convert, will take\n# longer if we keep the QC variables. Faseter if we exclude them.\n# The method will return a dataset. In this case the dataset returned is the same\n# dataset.\nskip_variables = [ii for ii in ds.data_vars if ii.startswith('qc_')]\nnew_ds = ds.utils.change_units(variables=None, desired_unit='m', skip_variables=skip_variables)\nprint('Variables changed back to m by looping over all variables in dataset')\nprint('Orginal dataset is same as retured dataset:', ds is new_ds)\nprint_summary(new_ds, variables)\n\n# For coordinate variables need to explicitly give coordinage variable name and use\n# the returned dataset. The xarray method used to change values on coordinate\n# values requries returning a new updated dataet.\nvar_name = 'range'\nvariables.append(var_name)\nnew_ds = ds.utils.change_units(variables=variables, desired_unit='km')\nprint('Variables and coordinate variable values changed to km')\nprint('Orginal dataset is same as retured dataset:', ds is new_ds)\nprint_summary(new_ds, variables)" ] } ], "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.14.3" } }, "nbformat": 4, "nbformat_minor": 0 }