Reputation: 1275
I have 2 xarray objects. I would like to check if these 2 arrays have the same dimensions and coordinates. But the two objects don't need to have the same values or meta data.
For example:
import xarray as xr
arr1_data = [[1, 2], [3, 4]]
arr2_data = [[5, 6], [7, 8]]
arr1 = xr.DataArray(arr1_data, dims=["y", "x"], coords={"y": ["coord1", "coord2"]})
arr2 = xr.DataArray(arr2_data, dims=["y", "x"], coords={"y": ["coord1", "coord2"]})
compare_xarray_objects(arr1, arr2) # Should return True
The .dims
attribute returns a tuple, so it is easy to tell if dimensions are the same. But .coords
attribute returns a DataArrayCoordinates
object and I don't know how to compare a DataArrayCoordinates
object with another one.
Upvotes: 4
Views: 2091
Reputation: 15442
For cases like the one in your example where you're trying to compare indexing coordinates, simply use xr.align
with the join='exact'
argument.
xr.align(arr1, arr2, join='exact') # will raise a ValueError if not aligned
If you're trying to also compare non-indexing coordinates, you could also use xr.testing.assert_equal
. This will check all coordinates, including those not in the dimension of the array (e.g. if you had another coordinate z
indexed by x
and y
). However, it's a bit pickier than xr.align
, as it requires the dimension ordering to be the same. If this were an issue, you could loop through the non-indexing coordinates and use this testing function to check equality for each coordinate.
Upvotes: 3