<jupyter_start><jupyter_text>Workshop 3:  netCDF, xarray, pandas Part III:  Advanced xarrayWe can apply many of the same operations on xarray DataArrays as with pandas Series/DataFrames and numpy ndarrays.<jupyter_code>import numpy as np
import xarray as xr
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
ds = xr.open_dataset('data/gistemp1200_GHCNv4_ERSSTv5.nc')<jupyter_output><empty_output><jupyter_text>BroadcastingBroadcasting arrays in numpy is a nightmare. It is much easier when the data axes are labeled!This is a useless calculation, but it illustrates how perfoming an operation on arrays with differenty coordinates will result in automatic broadcasting<jupyter_code>lon_times_lat = ds.lon * ds.lat
lon_times_lat
lon_times_lat.plot()<jupyter_output><empty_output><jupyter_text>ReductionsJust like in numpy, we can reduce xarray DataArrays along any number of axes:<jupyter_code>ds.tempanomaly.mean(axis=0).dims
ds.tempanomaly.mean(axis=1).dims<jupyter_output><empty_output><jupyter_text>However, rather than performing reductions on axes (as in numpy), we can perform them on dimensions. This turns out to be a huge convenience<jupyter_code>ds_zonal_mean = ds.mean(dim='lon')
ds_zonal_mean
ds_zonal_mean.tempanomaly.plot()
ds_zonal_mean.tempanomaly.std('time').plot()<jupyter_output><empty_output><jupyter_text>RollingSimilar to the `resample` method we used in the previous exercise, we can calculate the running mean to smooth signals.<jupyter_code>example = ds.sel({'lat':0, 'lon':0}, method='nearest').tempanomaly
ds_rolling = example.rolling(time=5*12, center=True).mean()
example.plot(alpha=.3)
ds_rolling.plot()  # notice the missing values at either end<jupyter_output><empty_output><jupyter_text>access the time You can access time properties with the `dt` accessor.<jupyter_code>ds.time.dt.year<jupyter_output><empty_output><jupyter_text>Exercises 1. Calculate the standard deviation of the monthly and annual temperatures and create two maps thereof in a single figure. 2. Calculate the linear trend of a temperature time series above in [$^\circ$C/century].  Solutions<jupyter_code># 1. Calculate the standard deviation of the monthly and annual temperatures 
# and create two maps thereof in a single figure.
fig, ax = plt.subplots(1, 2, figsize=(10,5), sharey=True)
ds.tempanomaly.std('time').plot(ax=ax[0])
ds.tempanomaly.rolling(time=12, center=True).mean().std('time').plot(ax=ax[1])
# 2. Calculate the linear trend of a temperature time series above in [$^\circ$C/century].
pf = np.polyfit(example.time.dt.year+example.time.dt.month/12, example, deg=1)
print(f'The temperature increase is {pf[0]*100:.1f} K/century')<jupyter_output>The temperature increase is 1.0 K/century
{'fraction_non_alphanumeric': 0.09864319765309865, 'fraction_numerical': 0.013934726806013934, 'mean_word_length': 6.861671469740634, 'pattern_counts': {'":': 0, '<': 28, '<?xml version=': 0, '>': 28, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '7', 'dir': 'jupyter-structured-clean-dedup', 'id': '235408', 'license': 'BSD-3-Clause', 'n_tokens_mistral': 911, 'n_tokens_neox': 868, 'n_words': 263, 'path': '3c_xarray.ipynb', 'repo_name': 'AJueling/python_climate_physics', 'size': '2727'}