[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M76ZJ8ASZ4QYQ70Y6SBA4Z4S":3,"skill-same:01M76ZJ8ASZ4QYQ70Y6SBA4Z4S":50},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":28,"commitSha":29,"skillDirectory":30,"forksCount":31,"repositoryHtmlUrl":32,"repositoryHomepageUrl":6,"ownerHtmlUrl":33,"ownerBlogUrl":34,"ownerDescription":6,"updatedAt":35,"install":36,"resources":49},"01M76ZJ8ASZ4QYQ70Y6SBA4Z4S","xarray",null,"N-dimensional labeled arrays and datasets in Python. Built on top of NumPy and Dask. It introduces labels in the form of dimensions, coordinates, and attributes on top of raw NumPy-like arrays, making data analysis in physical sciences more intuitive and less error-prone. Use for working with multi-dimensional scientific data, NetCDF\u002FGRIB\u002FZarr files, climate\u002Fweather\u002Foceanographic datasets, remote sensing, geospatial imaging, large out-of-memory datasets with Dask, and labeled array operations.","stanfish06\u002Fskillquarium","stanfish06","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F93099613?v=4","01M75F1CK4ZW109ZK3T26VN52F","Zhiyuan","01M75F1CM53VH6F79DZ8GXKKES",12,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Fxarray\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: xarray\ndescription: N-dimensional labeled arrays and datasets in Python. Built on top of NumPy and Dask. It introduces labels in the form of dimensions, coordinates, and attributes on top of raw NumPy-like arrays, making data analysis in physical sciences more intuitive and less error-prone. Use for working with multi-dimensional scientific data, NetCDF\u002FGRIB\u002FZarr files, climate\u002Fweather\u002Foceanographic datasets, remote sensing, geospatial imaging, large out-of-memory datasets with Dask, and labeled array operations.\ncompatibility: Requires Python 3.11+ and xarray 2026.04.0+. Install with `uv pip install \"xarray[io,parallel]\"` for NetCDF\u002FZarr I\u002FO and Dask support. Zarr I\u002FO now requires zarr>=3.0 (included with `xarray[io]`). Cloud I\u002FO (S3\u002FGCS) additionally needs s3fs or gcsfs.\nlicense: Apache-2.0\nmetadata: {\"version\": \"1.2\", \"skill-author\": \"K-Dense Inc.\"}\n---\n\n# Xarray - N-Dimensional Labeled Arrays\n\nXarray provides a pandas-like experience for multidimensional data. It is the core of the Pangeo ecosystem and is essential for working with NetCDF, GRIB, and Zarr formats.\n\n> [!WARNING]\n> **Breaking changes through xarray 2026.09.0** (the current release, up from 2024.01 when this skill was first written):\n> 1. **Zarr v3 required**: `xarray[io]` now installs `zarr>=3.0`; if your environment pins `zarr\u003C3`, Zarr I\u002FO will fail. As of 2026.09.0 the remaining zarr-python 2 compatibility code has been removed entirely.\n> 2. **Timedelta decode default changed**: `open_dataset()` no longer decodes `np.timedelta64` from units-only attributes by default. Pass `decode_timedelta=True` to restore the previous behavior.\n> 3. **netCDF preferred engine**: The default backend order reverted to `netCDF4 > h5netcdf > scipy` in 2026.04.0 (after a temporary change in 2025.09.1). Explicitly specify `engine=` when reproducibility matters.\n> 4. **Bottleneck disabled by default** (2026.09.0): accelerated rolling\u002Freduction operations no longer use the optional `bottleneck` backend unless it is explicitly re-enabled; results are unaffected but performance characteristics may change.\n> 5. **Python 3.11 support ending**: 2026.09.0 is the last xarray release supporting Python 3.11 — the next release requires Python 3.12+.\n\n## When to Use\n\n- Working with multi-dimensional scientific data (Time, Lat, Lon, Level, Ensemble).\n- Analyzing climate, weather, or oceanographic datasets (NetCDF files).\n- Handling large datasets that don't fit in memory (via Dask integration).\n- Performing complex broadcasting and alignment based on dimension names instead of axis indices.\n- Storing metadata (units, descriptions) directly inside the data object.\n- Remote sensing and geospatial imaging analysis.\n\n## Reference Documentation\n\n**Official docs**: https:\u002F\u002Fdocs.xarray.dev\u002F  \n**Tutorials**: https:\u002F\u002Ftutorial.xarray.dev\u002F  \n**Search patterns**: `xr.DataArray`, `xr.Dataset`, `ds.sel`, `ds.groupby`, `ds.resample`, `xr.open_dataset`\n\n## Core Principles\n\n### DataArray vs Dataset\n\n| Structure | Description | Analogy |\n|-----------|-------------|--------|\n| DataArray | A single labeled N-dimensional array. | Like a pandas.Series but N-D. |\n| Dataset | A dict-like container of multiple DataArrays. | Like a pandas.DataFrame but N-D. |\n\n### Key Concepts\n\n- **Dimensions**: Names of the axes (e.g., x, y, time).\n- **Coordinates**: Values associated with dimensions (e.g., actual timestamps or latitude values).\n- **Attributes**: Arbitrary metadata (e.g., units='Kelvin', standard_name='air_temperature').\n\n## Quick Reference\n\n### Installation\n\n```bash\n# Create and activate an isolated environment\nuv venv\nsource .venv\u002Fbin\u002Factivate\n\n# Recommended: io extra includes netCDF4, h5netcdf, zarr (v3), scipy; parallel adds Dask\nuv pip install \"xarray[io,parallel]\"\n\n# Minimal install (no I\u002FO extras)\nuv pip install xarray\n\n# Full install with visualization and acceleration\nuv pip install \"xarray[complete]\"\n```\n\n### Standard Imports\n\n```python\nimport xarray as xr\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n```\n\n### Basic Pattern - Creation\n\n```python\nimport xarray as xr\nimport numpy as np\n\n# Create a DataArray\ndata = np.random.rand(4, 3)\ntimes = pd.date_range(\"2023-01-01\", periods=4)\nlons = [-120, -110, -100]\n\nda = xr.DataArray(\n    data, \n    coords={\"time\": times, \"lon\": lons}, \n    dims=(\"time\", \"lon\"),\n    name=\"temp\",\n    attrs={\"units\": \"degC\"}\n)\n\n# Convert to Dataset\nds = da.to_dataset()\nprint(ds)\n```\n\n## Critical Rules\n\n### ✅ DO\n\n- **Use Named Dimensions** - Always use `dim=('time', 'lat', 'lon')` instead of integer axes.\n- **Select by Labels** - Use `.sel()` for coordinate values and `.isel()` for index integers.\n- **Lazy Loading** - Use `chunks={}` in `open_dataset` to handle large files with Dask.\n- **Keep Metadata** - Populate `.attrs` to ensure your data is self-describing.\n- **Alignment** - Let Xarray handle broadcasting; it will automatically align data based on coordinate values.\n- **Accessor power** - Use `.dt` for datetime and `.str` for string operations.\n\n### ❌ DON'T\n\n- **Use Integer Indexing** - Avoid `data[0, :, 5]` (unreadable and fragile). Use `.isel(time=0, lon=5)`.\n- **Ignore the Encoding** - When saving to NetCDF, check `ds.encoding` for compression\u002Fscaling.\n- **Manual Loops** - Don't loop over time steps; use `.groupby()` or `.resample()`.\n- **Forget Dask** - For datasets larger than RAM, ensure Dask is installed and chunks are defined.\n\n## Anti-Patterns (NEVER)\n\n```python\n# ❌ BAD: Positional indexing (What is axis 1? Lat or Lon?)\nmean_val = ds.variable.mean(axis=1)\n\n# ✅ GOOD: Named dimension reduction (Clear and robust)\nmean_val = ds.variable.mean(dim='lat')\n\n# ❌ BAD: Manual time slicing with list comprehensions\n# subset = [ds.sel(time=t) for t in my_times if t > '2020-01-01']\n\n# ✅ GOOD: Built-in slicing\nsubset = ds.sel(time=slice('2020-01-01', '2021-12-31'))\n\n# ❌ BAD: Losing metadata during numpy conversion\nraw_data = ds.temp.values # Now it's just a numpy array, units are gone!\n\n# ✅ GOOD: Keep in Xarray as long as possible\nprocessed = ds.temp * 10 # Units and coords are preserved\n```\n\n## Selection and Indexing\n\n### sel vs isel\n\n```python\n# Select by coordinate values\nsubset = ds.sel(lat=45.0, lon=slice(-100, -80))\n\n# Select by index (integer)\nfirst_step = ds.isel(time=0)\n\n# Nearest neighbor lookup\npoint = ds.sel(lat=42.1, lon=-71.2, method=\"nearest\")\n\n# Multi-dimensional selection\nhigh_temp_days = ds.where(ds.temp > 30, drop=True)\n```\n\n## Computation and Math\n\n### Broadcasting and Alignment\n\n```python\n# Xarray aligns automatically by coordinate names\nda1 = xr.DataArray([1, 2], coords=[[1, 2]], dims=['x'])\nda2 = xr.DataArray([1, 2, 3], coords=[[1, 2, 3]], dims=['y'])\n\n# result is a 2x3 matrix\nresult = da1 + da2 \n\n# Mathematical operations preserve coordinates\nlog_temp = np.log(ds.temp)\nanomalies = ds.temp - ds.temp.mean(dim='time')\n```\n\n## GroupBy and Resampling\n\n### Time Series and Spatial Aggregation\n\n```python\n# Monthly means\nmonthly = ds.resample(time=\"1MS\").mean()\n\n# Climatology (group by month regardless of year)\nclimatology = ds.groupby(\"time.month\").mean()\n\n# Calculate anomalies relative to climatology\nanomalies = ds.groupby(\"time.month\") - climatology\n\n# Rolling window (Moving average)\nrolling_mean = ds.rolling(time=7, center=True).mean()\n```\n\n## File I\u002FO (NetCDF, Zarr)\n\n### Reading and Writing\n\n```python\n# Open a single file (explicit engine avoids default-engine ambiguity)\nds = xr.open_dataset(\"weather_data.nc\", engine=\"netcdf4\")\n\n# Open multiple files (MFDataset)\nds_all = xr.open_mfdataset(\"data\u002F*.nc\", combine=\"by_coords\", chunks={'time': 100})\n\n# Write to NetCDF\nds.to_netcdf(\"output.nc\")\n\n# Write to Zarr (requires zarr>=3.0 with xarray 2026.04.0+)\nds.to_zarr(\"data.zarr\")\n```\n\n## Plotting\n\n### High-level wrapping of Matplotlib\n\n```python\n# 1D plot\nds.temp.sel(lat=0, lon=0, method='nearest').plot()\n\n# 2D map\nds.temp.isel(time=0).plot(cmap='RdBu_r', robust=True)\n\n# Faceting (Subplots)\nds.temp.isel(time=slice(0, 4)).plot(col=\"time\", col_wrap=2)\n```\n\n## Integration with pandas and NumPy\n\n```python\n# To Pandas\ndf = ds.to_dataframe()\n\n# From Pandas\nnew_ds = xr.Dataset.from_dataframe(df)\n\n# To NumPy (Lose coordinates)\narr = ds.temp.values\n\n# Interoperability\n# Xarray objects work in many SciPy\u002FNumPy functions\nfrom scipy.signal import detrend\ndetrended = xr.apply_ufunc(detrend, ds.temp, input_core_dims=[['time']], output_core_dims=[['time']])\n```\n\n## Advanced: Dask for Big Data\n\n### Out-of-memory computation\n\n```python\n# Opening with chunks creates Dask arrays\nds = xr.open_dataset(\"huge_file.nc\", chunks={'time': 500, 'lat': 100, 'lon': 100})\n\n# Computation is now lazy\nresult = ds.temp.mean(dim='time') # Returns immediately\n\n# Trigger computation\nfinal_val = result.compute()\n```\n\n## Practical Workflows\n\n### 1. Global Temperature Anomaly Workflow\n\n```python\ndef calculate_temp_anomaly(filepath):\n    \"\"\"Calculate monthly anomalies from NetCDF data.\"\"\"\n    ds = xr.open_dataset(filepath, engine=\"netcdf4\")\n    \n    # 1. Compute climatology (mean for each month of the year)\n    climatology = ds.temp.groupby(\"time.month\").mean(\"time\")\n    \n    # 2. Subtract climatology from original data\n    anomalies = ds.temp.groupby(\"time.month\") - climatology\n    \n    # 3. Global mean anomaly\n    # Weighted by cos(lat) because grid cells get smaller at poles\n    weights = np.cos(np.deg2rad(ds.lat))\n    weights.name = \"weights\"\n    anom_weighted = anomalies.weighted(weights)\n    \n    return anom_weighted.mean((\"lat\", \"lon\"))\n\n# ts_anomaly = calculate_temp_anomaly(\"global_temps.nc\")\n```\n\n### 2. Multi-Model Ensemble Analysis\n\n```python\ndef analyze_ensemble(file_list):\n    \"\"\"Combine multiple model runs into a single dataset with a 'model' dimension.\"\"\"\n    datasets = [xr.open_dataset(f) for f in file_list]\n    model_names = [\"Model_A\", \"Model_B\", \"Model_C\"]\n    \n    # Concatenate along a new dimension\n    combined = xr.concat(datasets, dim=pd.Index(model_names, name=\"model\"))\n    \n    # Calculate ensemble mean and spread\n    ens_mean = combined.mean(dim=\"model\")\n    ens_std = combined.std(dim=\"model\")\n    \n    return ens_mean, ens_std\n```\n\n### 3. Satellite Image Processing (NDVI)\n\n```python\ndef calculate_ndvi(ds):\n    \"\"\"Calculate NDVI from Red and NIR bands in an Xarray Dataset.\"\"\"\n    # NDVI = (NIR - Red) \u002F (NIR + Red)\n    red = ds.sel(band='red')\n    nir = ds.sel(band='nir')\n    \n    ndvi = (nir - red) \u002F (nir + red)\n    ndvi.attrs['long_name'] = \"Normalized Difference Vegetation Index\"\n    \n    return ndvi\n```\n\n## Performance Optimization\n\n### Chunking Strategies\n\n```python\n# ❌ Problem: Small chunks lead to massive overhead\n# ds = ds.chunk({'time': 1, 'lat': 1, 'lon': 1})\n\n# ✅ Solution: Aim for 10MB - 100MB per chunk\nds = ds.chunk({'time': -1, 'lat': 100, 'lon': 100})\n```\n\n### Vectorization with apply_ufunc\n\n```python\n# Wrap a custom numpy function to work on Xarray objects efficiently\ndef my_complex_stat(x):\n    return np.median(x) * np.std(x)\n\nresult = xr.apply_ufunc(\n    my_complex_stat, \n    ds.temp,\n    input_core_dims=[['time']], # The dimension to map the function over\n    vectorize=True,\n    dask=\"parallelized\"\n)\n```\n\n## Common Pitfalls and Solutions\n\n### Coordinate Mismatch\n\n```python\n# ❌ Problem: DataArrays don't align due to floating point jitter in lat\u002Flon\n# ✅ Solution: Use .interp_like() or .reindex_like()\nds2_aligned = ds2.interp_like(ds1)\n```\n\n### Memory Leak with values\n\n```python\n# ❌ Problem: Calling .values on a huge Dask-backed array crashes the machine\n# ✅ Solution: Use .compute() or subset first\nsubset_val = ds.temp.isel(time=0).values # This is safer\n```\n\n### Slicing issues (Start\u002FEnd)\n\n```python\n# ❌ Problem: slice(10, 0) returns empty because order is wrong\n# ✅ Solution: Check if your index is ascending or descending\n# ds.sortby('lat').sel(lat=slice(-90, 90))\n```\n\nXarray is the bridge between raw N-dimensional math and high-level data analysis. Its ability to handle labels and metadata makes scientific code self-documenting and significantly more reliable.\n","# Xarray - N-Dimensional Labeled Arrays\n\nXarray provides a pandas-like experience for multidimensional data. It is the core of the Pangeo ecosystem and is essential for working with NetCDF, GRIB, and Zarr formats.\n\n> [!WARNING]\n> **Breaking changes through xarray 2026.09.0** (the current release, up from 2024.01 when this skill was first written):\n> 1. **Zarr v3 required**: `xarray[io]` now installs `zarr>=3.0`; if your environment pins `zarr\u003C3`, Zarr I\u002FO will fail. As of 2026.09.0 the remaining zarr-python 2 compatibility code has been removed entirely.\n> 2. **Timedelta decode default changed**: `open_dataset()` no longer decodes `np.timedelta64` from units-only attributes by default. Pass `decode_timedelta=True` to restore the previous behavior.\n> 3. **netCDF preferred engine**: The default backend order reverted to `netCDF4 > h5netcdf > scipy` in 2026.04.0 (after a temporary change in 2025.09.1). Explicitly specify `engine=` when reproducibility matters.\n> 4. **Bottleneck disabled by default** (2026.09.0): accelerated rolling\u002Freduction operations no longer use the optional `bottleneck` backend unless it is explicitly re-enabled; results are unaffected but performance characteristics may change.\n> 5. **Python 3.11 support ending**: 2026.09.0 is the last xarray release supporting Python 3.11 — the next release requires Python 3.12+.\n\n## When to Use\n\n- Working with multi-dimensional scientific data (Time, Lat, Lon, Level, Ensemble).\n- Analyzing climate, weather, or oceanographic datasets (NetCDF files).\n- Handling large datasets that don't fit in memory (via Dask integration).\n- Performing complex broadcasting and alignment based on dimension names instead of axis indices.\n- Storing metadata (units, descriptions) directly inside the data object.\n- Remote sensing and geospatial imaging analysis.\n\n## Reference Documentation\n\n**Official docs**: https:\u002F\u002Fdocs.xarray.dev\u002F  \n**Tutorials**: https:\u002F\u002Ftutorial.xarray.dev\u002F  \n**Search patterns**: `xr.DataArray`, `xr.Dataset`, `ds.sel`, `ds.groupby`, `ds.resample`, `xr.open_dataset`\n\n## Core Principles\n\n### DataArray vs Dataset\n\n| Structure | Description | Analogy |\n|-----------|-------------|--------|\n| DataArray | A single labeled N-dimensional array. | Like a pandas.Series but N-D. |\n| Dataset | A dict-like container of multiple DataArrays. | Like a pandas.DataFrame but N-D. |\n\n### Key Concepts\n\n- **Dimensions**: Names of the axes (e.g., x, y, time).\n- **Coordinates**: Values associated with dimensions (e.g., actual timestamps or latitude values).\n- **Attributes**: Arbitrary metadata (e.g., units='Kelvin', standard_name='air_temperature').\n\n## Quick Reference\n\n### Installation\n\n```bash\n# Create and activate an isolated environment\nuv venv\nsource .venv\u002Fbin\u002Factivate\n\n# Recommended: io extra includes netCDF4, h5netcdf, zarr (v3), scipy; parallel adds Dask\nuv pip install \"xarray[io,parallel]\"\n\n# Minimal install (no I\u002FO extras)\nuv pip install xarray\n\n# Full install with visualization and acceleration\nuv pip install \"xarray[complete]\"\n```\n\n### Standard Imports\n\n```python\nimport xarray as xr\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n```\n\n### Basic Pattern - Creation\n\n```python\nimport xarray as xr\nimport numpy as np\n\n# Create a DataArray\ndata = np.random.rand(4, 3)\ntimes = pd.date_range(\"2023-01-01\", periods=4)\nlons = [-120, -110, -100]\n\nda = xr.DataArray(\n    data, \n    coords={\"time\": times, \"lon\": lons}, \n    dims=(\"time\", \"lon\"),\n    name=\"temp\",\n    attrs={\"units\": \"degC\"}\n)\n\n# Convert to Dataset\nds = da.to_dataset()\nprint(ds)\n```\n\n## Critical Rules\n\n### ✅ DO\n\n- **Use Named Dimensions** - Always use `dim=('time', 'lat', 'lon')` instead of integer axes.\n- **Select by Labels** - Use `.sel()` for coordinate values and `.isel()` for index integers.\n- **Lazy Loading** - Use `chunks={}` in `open_dataset` to handle large files with Dask.\n- **Keep Metadata** - Populate `.attrs` to ensure your data is self-describing.\n- **Alignment** - Let Xarray handle broadcasting; it will automatically align data based on coordinate values.\n- **Accessor power** - Use `.dt` for datetime and `.str` for string operations.\n\n### ❌ DON'T\n\n- **Use Integer Indexing** - Avoid `data[0, :, 5]` (unreadable and fragile). Use `.isel(time=0, lon=5)`.\n- **Ignore the Encoding** - When saving to NetCDF, check `ds.encoding` for compression\u002Fscaling.\n- **Manual Loops** - Don't loop over time steps; use `.groupby()` or `.resample()`.\n- **Forget Dask** - For datasets larger than RAM, ensure Dask is installed and chunks are defined.\n\n## Anti-Patterns (NEVER)\n\n```python\n# ❌ BAD: Positional indexing (What is axis 1? Lat or Lon?)\nmean_val = ds.variable.mean(axis=1)\n\n# ✅ GOOD: Named dimension reduction (Clear and robust)\nmean_val = ds.variable.mean(dim='lat')\n\n# ❌ BAD: Manual time slicing with list comprehensions\n# subset = [ds.sel(time=t) for t in my_times if t > '2020-01-01']\n\n# ✅ GOOD: Built-in slicing\nsubset = ds.sel(time=slice('2020-01-01', '2021-12-31'))\n\n# ❌ BAD: Losing metadata during numpy conversion\nraw_data = ds.temp.values # Now it's just a numpy array, units are gone!\n\n# ✅ GOOD: Keep in Xarray as long as possible\nprocessed = ds.temp * 10 # Units and coords are preserved\n```\n\n## Selection and Indexing\n\n### sel vs isel\n\n```python\n# Select by coordinate values\nsubset = ds.sel(lat=45.0, lon=slice(-100, -80))\n\n# Select by index (integer)\nfirst_step = ds.isel(time=0)\n\n# Nearest neighbor lookup\npoint = ds.sel(lat=42.1, lon=-71.2, method=\"nearest\")\n\n# Multi-dimensional selection\nhigh_temp_days = ds.where(ds.temp > 30, drop=True)\n```\n\n## Computation and Math\n\n### Broadcasting and Alignment\n\n```python\n# Xarray aligns automatically by coordinate names\nda1 = xr.DataArray([1, 2], coords=[[1, 2]], dims=['x'])\nda2 = xr.DataArray([1, 2, 3], coords=[[1, 2, 3]], dims=['y'])\n\n# result is a 2x3 matrix\nresult = da1 + da2 \n\n# Mathematical operations preserve coordinates\nlog_temp = np.log(ds.temp)\nanomalies = ds.temp - ds.temp.mean(dim='time')\n```\n\n## GroupBy and Resampling\n\n### Time Series and Spatial Aggregation\n\n```python\n# Monthly means\nmonthly = ds.resample(time=\"1MS\").mean()\n\n# Climatology (group by month regardless of year)\nclimatology = ds.groupby(\"time.month\").mean()\n\n# Calculate anomalies relative to climatology\nanomalies = ds.groupby(\"time.month\") - climatology\n\n# Rolling window (Moving average)\nrolling_mean = ds.rolling(time=7, center=True).mean()\n```\n\n## File I\u002FO (NetCDF, Zarr)\n\n### Reading and Writing\n\n```python\n# Open a single file (explicit engine avoids default-engine ambiguity)\nds = xr.open_dataset(\"weather_data.nc\", engine=\"netcdf4\")\n\n# Open multiple files (MFDataset)\nds_all = xr.open_mfdataset(\"data\u002F*.nc\", combine=\"by_coords\", chunks={'time': 100})\n\n# Write to NetCDF\nds.to_netcdf(\"output.nc\")\n\n# Write to Zarr (requires zarr>=3.0 with xarray 2026.04.0+)\nds.to_zarr(\"data.zarr\")\n```\n\n## Plotting\n\n### High-level wrapping of Matplotlib\n\n```python\n# 1D plot\nds.temp.sel(lat=0, lon=0, method='nearest').plot()\n\n# 2D map\nds.temp.isel(time=0).plot(cmap='RdBu_r', robust=True)\n\n# Faceting (Subplots)\nds.temp.isel(time=slice(0, 4)).plot(col=\"time\", col_wrap=2)\n```\n\n## Integration with pandas and NumPy\n\n```python\n# To Pandas\ndf = ds.to_dataframe()\n\n# From Pandas\nnew_ds = xr.Dataset.from_dataframe(df)\n\n# To NumPy (Lose coordinates)\narr = ds.temp.values\n\n# Interoperability\n# Xarray objects work in many SciPy\u002FNumPy functions\nfrom scipy.signal import detrend\ndetrended = xr.apply_ufunc(detrend, ds.temp, input_core_dims=[['time']], output_core_dims=[['time']])\n```\n\n## Advanced: Dask for Big Data\n\n### Out-of-memory computation\n\n```python\n# Opening with chunks creates Dask arrays\nds = xr.open_dataset(\"huge_file.nc\", chunks={'time': 500, 'lat': 100, 'lon': 100})\n\n# Computation is now lazy\nresult = ds.temp.mean(dim='time') # Returns immediately\n\n# Trigger computation\nfinal_val = result.compute()\n```\n\n## Practical Workflows\n\n### 1. Global Temperature Anomaly Workflow\n\n```python\ndef calculate_temp_anomaly(filepath):\n    \"\"\"Calculate monthly anomalies from NetCDF data.\"\"\"\n    ds = xr.open_dataset(filepath, engine=\"netcdf4\")\n    \n    # 1. Compute climatology (mean for each month of the year)\n    climatology = ds.temp.groupby(\"time.month\").mean(\"time\")\n    \n    # 2. Subtract climatology from original data\n    anomalies = ds.temp.groupby(\"time.month\") - climatology\n    \n    # 3. Global mean anomaly\n    # Weighted by cos(lat) because grid cells get smaller at poles\n    weights = np.cos(np.deg2rad(ds.lat))\n    weights.name = \"weights\"\n    anom_weighted = anomalies.weighted(weights)\n    \n    return anom_weighted.mean((\"lat\", \"lon\"))\n\n# ts_anomaly = calculate_temp_anomaly(\"global_temps.nc\")\n```\n\n### 2. Multi-Model Ensemble Analysis\n\n```python\ndef analyze_ensemble(file_list):\n    \"\"\"Combine multiple model runs into a single dataset with a 'model' dimension.\"\"\"\n    datasets = [xr.open_dataset(f) for f in file_list]\n    model_names = [\"Model_A\", \"Model_B\", \"Model_C\"]\n    \n    # Concatenate along a new dimension\n    combined = xr.concat(datasets, dim=pd.Index(model_names, name=\"model\"))\n    \n    # Calculate ensemble mean and spread\n    ens_mean = combined.mean(dim=\"model\")\n    ens_std = combined.std(dim=\"model\")\n    \n    return ens_mean, ens_std\n```\n\n### 3. Satellite Image Processing (NDVI)\n\n```python\ndef calculate_ndvi(ds):\n    \"\"\"Calculate NDVI from Red and NIR bands in an Xarray Dataset.\"\"\"\n    # NDVI = (NIR - Red) \u002F (NIR + Red)\n    red = ds.sel(band='red')\n    nir = ds.sel(band='nir')\n    \n    ndvi = (nir - red) \u002F (nir + red)\n    ndvi.attrs['long_name'] = \"Normalized Difference Vegetation Index\"\n    \n    return ndvi\n```\n\n## Performance Optimization\n\n### Chunking Strategies\n\n```python\n# ❌ Problem: Small chunks lead to massive overhead\n# ds = ds.chunk({'time': 1, 'lat': 1, 'lon': 1})\n\n# ✅ Solution: Aim for 10MB - 100MB per chunk\nds = ds.chunk({'time': -1, 'lat': 100, 'lon': 100})\n```\n\n### Vectorization with apply_ufunc\n\n```python\n# Wrap a custom numpy function to work on Xarray objects efficiently\ndef my_complex_stat(x):\n    return np.median(x) * np.std(x)\n\nresult = xr.apply_ufunc(\n    my_complex_stat, \n    ds.temp,\n    input_core_dims=[['time']], # The dimension to map the function over\n    vectorize=True,\n    dask=\"parallelized\"\n)\n```\n\n## Common Pitfalls and Solutions\n\n### Coordinate Mismatch\n\n```python\n# ❌ Problem: DataArrays don't align due to floating point jitter in lat\u002Flon\n# ✅ Solution: Use .interp_like() or .reindex_like()\nds2_aligned = ds2.interp_like(ds1)\n```\n\n### Memory Leak with values\n\n```python\n# ❌ Problem: Calling .values on a huge Dask-backed array crashes the machine\n# ✅ Solution: Use .compute() or subset first\nsubset_val = ds.temp.isel(time=0).values # This is safer\n```\n\n### Slicing issues (Start\u002FEnd)\n\n```python\n# ❌ Problem: slice(10, 0) returns empty because order is wrong\n# ✅ Solution: Check if your index is ascending or descending\n# ds.sortby('lat').sel(lat=slice(-90, 90))\n```\n\nXarray is the bridge between raw N-dimensional math and high-level data analysis. Its ability to handle labels and metadata makes scientific code self-documenting and significantly more reliable.\n",{"name":5,"license":15,"metadata":24,"description":7,"compatibility":27},{"version":25,"skill-author":26},"1.2","K-Dense Inc.","Requires Python 3.11+ and xarray 2026.04.0+. Install with `uv pip install \"xarray[io,parallel]\"` for NetCDF\u002FZarr I\u002FO and Dask support. Zarr I\u002FO now requires zarr>=3.0 (included with `xarray[io]`). Cloud I\u002FO (S3\u002FGCS) additionally needs s3fs or gcsfs.","master","49e49abf2f670d429e0b7e2c0349739c3fdd5cbe","skills\u002Fxarray",5,"https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium","https:\u002F\u002Fgithub.com\u002Fstanfish06","https:\u002F\u002Fwww.stanfish.dev\u002F","2026-11-14 21:31:37",{"source":8,"skillName":5,"commands":37,"prompt":47,"zipAvailable":48},[38,41,44],{"tool":39,"command":40},"npx","npx skills add stanfish06\u002Fskillquarium --skill xarray",{"tool":42,"command":43},"bunx","bunx skills add stanfish06\u002Fskillquarium --skill xarray",{"tool":45,"command":46},"pnpm","pnpm dlx skills add stanfish06\u002Fskillquarium --skill xarray","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Fxarray\u002FSKILL.md",true,[],[51,59,67,74,81,89],{"skillNo":52,"name":53,"nameZh":6,"description":54,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":55,"licenseFileUrl":6,"sourceHtmlUrl":56,"categories":57,"keywords":58,"publishedAt":19},"01M76ZJTRVA456GD7K8Y3EP82H","zarr-python","Stores and queries chunked N-D scientific arrays with Zarr-Python 3, including codecs, sharding, S3\u002FGCS storage, and NumPy\u002FDask\u002FXarray integration. Use for array layout, bounded I\u002FO, format migration, or scientific metadata preservation.","MIT","https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Fzarr-python\u002FSKILL.md",[],[],{"skillNo":60,"name":61,"nameZh":6,"description":62,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":63,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":19},"01M76ZJQZ15Q1HKC5V85NHE325","yeet","Publish local changes to GitHub by confirming scope, committing intentionally, pushing the branch, and opening a draft PR through the GitHub app from this plugin, with `gh` used only as a fallback where connector coverage is insufficient.","https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Fyeet\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Fyeet\u002FSKILL.md",[],[],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":55,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":19},"01M76ZHFBXD6VXPQ02VCEG202B","writing-mstest-tests","Use when asked to fix, rewrite, update, improve, modernize, show corrected code for, or explain existing MSTest tests or MSTest-specific configuration. Use for \"review\" when corrected code or edits are wanted, even for one pasted assertion or passing tests with bad failure output. Covers expected\u002Factual labels; generic Boolean, collection, string, numeric, null, identity, exception, hard-cast, and object[] checks; TestContext\u002Flifecycle; timeout\u002Fcancellation; OS\u002FCI conditions, retry, cleanup, parallelization, MSTest.Sdk project setup, and MSTESTxxxx. Honor the installed MSTest version. DO NOT USE to design new test cases (code-testing), perform report-only audits, create project files rather than explain MSTest setup, run tests, migrate frameworks, or handle non-MSTest\u002Fnon-.NET code.","https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Fwriting-mstest-tests\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":55,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":19},"01M76ZDFDF4N88RH6HSYGS7GP2","wgs-prs","End-to-end WGS to polygenic risk score pipeline. Takes paired-end FASTQ files (or a pre-existing VCF) through nf-core\u002Fsarek for variant calling, applies VCF QC (normalisation, hard filtering, Ti\u002FTv and Het\u002FHom checks), then computes polygenic risk scores via the PGS Catalog. Fills the FASTQ to VCF gap upstream of the gwas-prs skill.","https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Fwgs-prs\u002FSKILL.md",[],[],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":85,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":19},"01M76ZCC1SC68J42QK4MDC8RCG","webapp-testing","Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.","https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Fwebapp-testing\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Fwebapp-testing\u002FSKILL.md",[],[],{"skillNo":90,"name":91,"nameZh":6,"description":92,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":93,"sourceHtmlUrl":94,"categories":95,"keywords":96,"publishedAt":19},"01M76ZBW3S6B0KV2WFJMKYK39V","web-artifacts-builder","Suite of tools for creating elaborate, multi-component claude.ai HTML artifacts using modern frontend web technologies (React, Tailwind CSS, shadcn\u002Fui). Use for complex artifacts requiring state management, routing, or shadcn\u002Fui components - not for simple single-file HTML\u002FJSX artifacts.","https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Fweb-artifacts-builder\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Fweb-artifacts-builder\u002FSKILL.md",[],[]]