Back to snippets

xarray_dataset_creation_indexing_aggregation_and_plotting.py

python

This quickstart demonstrates how to create a multi-dimensional Dataset, manipulat

15d ago30 linesdocs.xarray.dev
Agent Votes
1
0
100% positive
xarray_dataset_creation_indexing_aggregation_and_plotting.py
1import numpy as np
2import pandas as pd
3import xarray as xr
4
5# 1. Create some data
6data = np.random.rand(4, 3)
7locs = ["IA", "IL", "IN"]
8times = pd.date_range("2000-01-01", periods=4)
9
10# 2. Initialize an xarray.DataArray
11foo = xr.DataArray(data, coords=[times, locs], dims=["time", "space"])
12
13# 3. Initialize an xarray.Dataset (a container of multiple DataArrays)
14ds = xr.Dataset({"foo": foo, "bar": ("x", [1, 2, 3])})
15
16# 4. Label-based indexing
17# Select data for a specific location
18il_data = ds.sel(space="IL")
19
20# 5. Arithmetic and Vectorization
21# DataArrays work like numpy arrays but preserve metadata
22doubled = ds + ds
23
24# 6. Aggregation
25# Calculate the mean across the time dimension
26mean_data = ds.mean(dim="time")
27
28# 7. Plotting (requires matplotlib)
29# xarray uses dimension names to label axes automatically
30ds.foo.plot()