Xarray

Working with multi-dimensional labeled data using xarray

Python
# Working with multi-dimensional labeled data using xarray

import numpy as np
import pandas as pd
import xarray as xr
import matplotlib.pyplot as plt

# Generate sample data
times = pd.date_range('2023-01-01', periods=7)
latitudes = np.linspace(-90, 90, 10)
longitudes = np.linspace(-180, 180, 20)
temperature_data = 15 + 8 * np.random.randn(len(times), len(latitudes), len(longitudes))

# Create an xarray.Dataset
temperature_ds = xr.Dataset(
    {
        "temperature": (["time", "latitude", "longitude"], temperature_data)
    },
    coords={
        "time": times,
        "latitude": latitudes,
        "longitude": longitudes
    }
)

# Print the dataset
print(temperature_ds)

# Calculate the mean temperature over time
mean_temperature = temperature_ds.temperature.mean(dim="time")

# Plot the mean temperature
mean_temperature.plot(cmap="coolwarm")
plt.title("Mean Temperature Distribution")
plt.show()
<xarray.Dataset> Size: 11kB
Dimensions:      (time: 7, latitude: 10, longitude: 20)
Coordinates:
  * time         (time) datetime64[us] 56B 2023-01-01 2023-01-02 ... 2023-01-07
  * latitude     (latitude) float64 80B -90.0 -70.0 -50.0 ... 50.0 70.0 90.0
  * longitude    (longitude) float64 160B -180.0 -161.1 -142.1 ... 161.1 180.0
Data variables:
    temperature  (time, latitude, longitude) float64 11kB 2.41 10.71 ... 13.77