Creating a toy 3D Array contains hourly frequency, temperature and lat,lon coordinates

Viewed 68

I want to create a 3-dimensional dataarray that stores temperature datas with corresponding latitude and longtitude and time with the hourly frequency. So I did the coding as follows;

np.random.seed(123)

temperature_3d = 15 + 10 * np.random.randn(24,4,4)    # 3-dimensional
lat = np.random.uniform(low=-90, high=90, size=(1,4))
lon = np.random.uniform(low=-180, high=180, size=(1,4))

# round to two digits after decimal point
temperature_3d = np.around(temperature_3d, decimals=2)
lat , lon = np.around([lat, lon], decimals=2)
date_rng = pd.date_range(start='1/1/2018T01:00', end='1/2/2018', freq='H')
da = xr.DataArray(data=temperature_3d,
                  coords={"lat": (["x","y"], lat),
                          "lon": (["x","y"], lon), 
                          "day": date_rng},
                  dims=["x","y","day"])
                  
da

And I get this error,

ValueError: conflicting sizes for dimension 'x': length 24 on the data but length 1 on coordinate 'lat'

Dimensionally it's wrong and I can fix it while not including time yet, My goal is to create a dataarray with the 720x40x40 dimensions (timexlat,lonxtime).

I'm also new in this kind of libraries. So I would be appreciated with the suggestions.

1 Answers

It looks like the shapes need to be matched correctly.

Firstly as your temperature data is of the shape (24,4,4),

temperature_3d = 15 + 10 * np.random.randn(24,4,4)    # 3-dimensional

you will need to put the date first in your dims:

da = xr.DataArray(data=temperature_3d,
              coords={"lat": (["x","y"], lat),
                      "lon": (["x","y"], lon), 
                      "day": date_rng},
              dims=["day","x","y"])

Secondly, your lat and lon coords have a shape according to ["x","y"], so in the example you need a 4x4 grid for what the lat is at each point, and another 4x4 grid for the lon at each point. For this we can use np.meshgrid:

latgrid, longrid = np.meshgrid(lat,lon)

So, in full:

import numpy as np
import xarray as xa

np.random.seed(123)

temperature_3d = 15 + 10 * np.random.randn(24,4,4)    # 3-dimensional
lat = np.random.uniform(low=-90, high=90, size=(4))
lon = np.random.uniform(low=-180, high=180, size=(4))

# round to two digits after decimal point
temperature_3d = np.around(temperature_3d, decimals=2)
lat , lon = np.around([lat, lon], decimals=2)
latgrid, longrid = np.meshgrid(lat,lon)
date_rng = pd.date_range(start='1/1/2018T01:00', end='1/2/2018', freq='H')

da = xa.DataArray(data=temperature_3d,
              coords={"lat": (["x","y"], latgrid),
                      "lon": (["x","y"], longrid), 
                      "day": date_rng},
              dims=["day","x","y"])
da
Related