# 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()
Click Run or press shift + ENTER to run code