Xarray Python GIS Tutorial: Efficient Analysis of Multi-Dimensional Geospatial Data
- Anvita Shrivastava

- Jun 26
- 4 min read
Updated: Jun 30
Geospatial datasets are growing more complicated than ever before. Many types of geospatial datasets are now multi-dimensional and include things like satellite images, climate models, weather predictions, and environmental observations. Traditional Python libraries, such as numpy and pandas, are great for handling numeric and tabular data; however, they do not natively support labeled multi-dimensional datasets.
That's why xarray has become so popular. It offers an easy-to-use interface for working with labeled N-dimensional arrays, making it one of the best libraries for GIS professionals, data scientists, remote sensing professionals, and climate scientists alike.

What is Xarray?
Xarray is an open-source Python library used to manipulate and analyze labeled, multi-dimensional data arrays. It adds labels, coordinates, and additional properties (or metadata) on top of NumPy, thus simplifying the management of scientific datasets.
Unlike NumPy, which relies solely on the index/position of an item within the array, Xarray allows users to access data based on meaningful "coordinate" labels. These include:
Latitude
Longitude
Time
Elevation
Bands
This type of data access allows for cleaner, more readable, and less error-prone GIS workflows.
Key features include:
Support for labeled N-dimensional arrays
Native support for working with NetCDF and GRIB files
Works seamlessly with Dask to enable parallel processing
Works well with Rasterio, GeoPandas, Cartopy, and Matplotlib
Efficiency in managing large geospatial datasets
Built-in statistical and aggregation functions
Why Use Xarray for GIS?
Many geospatial datasets include multiple dimensions:
Time series satellite imagery
Climate simulations
Weather prediction models
Oceanographic observations
Air quality monitoring
Earth observation products
For example, a satellite dataset may contain:
Dimensions:
Time × Band × Latitude × LongitudeInstead of manually tracking array indexes, Xarray lets you reference dimensions by name.
Example:
temperature. sel(
time="2025-01-01",
latitude=40,
longitude=-105
)This improves both code readability and maintainability.
Installing Xarray
Install Xarray using pip:
pip install xarrayFor geospatial workflows, install additional libraries:
pip install rasterio geopandas matplotlib cartopy netCDF4 daskLoading Geospatial Data
One of Xarray's biggest strengths is reading NetCDF datasets.
import xarray as xr
dataset = xr.open_dataset("temperature.nc")
print(dataset)Example output:
Dimensions:
time: 365
lat: 180
lon: 360
Data variables:
temperature
precipitationThe dataset automatically includes dimensions, coordinates, metadata, and variables.
Understanding DataArray vs Dataset
Xarray provides two primary objects.
DataArray
Represents a single variable.
temp = dataset["temperature"]
print(temp)Think of it as a labeled NumPy array.
Dataset
Represents multiple DataArrays together.
Example:
Dataset
Variables:
Temperature
Humidity
Wind Speed
PressureSimilar to a collection of related Pandas DataFrames.
Exploring Dataset Information
View dimensions:
dataset. dimsView coordinates:
dataset.coordsView variables:
dataset.data_varsView metadata:
dataset.attrsSelecting Data by Coordinates
Instead of indexing manually:
temperature[10, 45, 80]Use labeled selection:
temperature. sel(
time="2024-06-15",
lat=40,
lon=-75
)Or index-based selection:
temperature. isel(
time=0,
lat=100,
lon=150
)Slicing Spatial Data
Extract a geographic region:
subset = dataset.sel(
lat=slice(20, 40),
lon=slice(-120, -80)
)This is ideal for analyzing specific study areas.
Working with Time Series
Select a time range:
subset = dataset.sel(
time=slice(
"2023-01-01",
"2023-12-31"
)
)Calculate monthly averages:
monthly = dataset.groupby(
"time.month"
).mean()Compute annual averages:
annual = dataset.resample(
time="Y"
).mean()Performing Statistical Analysis
Calculate the mean:
dataset.mean()Maximum:
dataset.max()Standard deviation:
dataset.std()Average temperature over time:
dataset.temperature.mean(dim="time")Spatial average:
dataset.temperature.mean(
dim=["lat", "lon"]
)Raster Calculations
Suppose you have vegetation index data.
Normalize values:
normalized = (
dataset. ndvi - dataset. ndvi.min()
) / (
dataset.ndvi.max() - dataset.ndvi.min()
)Threshold pixels:
forest = dataset.ndvi > 0.6Calculate anomalies:
anomaly = (
dataset.temperature -
dataset.temperature.mean(dim="time")
)Working with Large Datasets Using Dask
Xarray integrates directly with Dask.
dataset = xr.open_dataset(
"large_file.nc",
chunks={
"time": 100
}
)Operations execute lazily.
result = dataset.mean(dim="time")Nothing is computed until:
result.compute()This allows processing datasets that exceed available RAM.
Visualizing Geospatial Data
Plot a raster:
dataset.temperature.isel(
time=0
).plot()Time series:
dataset.temperature.mean(
dim=["lat", "lon"]
).plot()Histogram:
dataset.temperature.plot.hist()Xarray automatically integrates with Matplotlib for high-quality visualizations.
Saving Processed Data
Save to NetCDF:
dataset.to_netcdf(
"processed_data.nc"
)Export a DataArray:
temperature.to_netcdf(
"temperature.nc"
)Benefits of Xarray
User-friendly labeled data structures.
Great compatibility with scientific file formats
Rapidly processing vast datasets.
Natural integration with GIS
Great visualization capabilities
Scalable parallel computation
Smooth integration into the scientific Python ecosystem
Xarray is a powerful Python library for working with GIS and geospatial data. With its labeled multi-dimensional array architecture, users can create many intricate workflows related to working with satellite data, climate models, meteorological forecasts, and environmental measurements. When paired with Dask, Rasterio, and GeoPandas, Xarray can conduct efficient, scalable, and readable geospatial analyses of data sets that range from local to worldwide.
If you're working with NetCDF, raster analysis, time series data, or even large GIS projects, becoming proficient with Xarray will enhance your productivity and the quality of your geospatial work by allowing you to manage large data sets more easily, write more organized code, and extract more meaningful insights from multi-dimensional geospatial datasets. By adding Xarray to your GIS library in Python, you will have the ability to efficiently process enormous amounts of data, produce cleaner code, and extract more significant insights from your multi-dimensional geospatial datasets.
To learn more about Xarray and its geospatial capabilities, click here.
For more information or any questions regarding the LizardTech suite of products, please don't hesitate to contact us at:
Email: info@geowgs84.com
USA (HQ): (720) 702–4849
(A GeoWGS84 Corp Company)




Comments