I would like to multiply two data arrays of same dimensions:
print(data1)
<xarray.DataArray 'var' (lat: 2160, lon: 4320)>
[9331200 values with dtype=int8]
Coordinates:
* lon (lon) float64 -180.0 -179.9 -179.8 -179.7 ... 179.8 179.9 180.0
* lat (lat) float64 89.96 89.88 89.79 89.71 ... -89.79 -89.88 -89.96
print(data2)
<xarray.DataArray 'var' (lat: 2160, lon: 4320)>
[9331200 values with dtype=float32]
Coordinates:
* lon (lon) float64 -180.0 -179.9 -179.8 -179.7 ... 179.8 179.9 180.0
* lat (lat) float64 89.96 89.88 89.79 89.71 ... -89.79 -89.87 -89.96
data1 * data2
returns this error:
ValueError: Cannot apply_along_axis when any iteration dimensions are 0
Note that following this thread, I made sure to have consistent dimensions and re-indexed both data arrays.
Since both arrays have different dtype
, I have tried data1.astype(np.float64) * data2
, but that returned the same error.
On the other hand, this returned an empty array:
data3 = data1.astype(np.float64) * data2.astype(np.float64)
print(data3)
<xarray.DataArray 'var' (lat: 0, lon: 0)>
array([], shape=(0, 0), dtype=float64)
Coordinates:
* lon (lon) float64
* lat (lat) float64
The only way I found to achieve this multiplication was to get the underlying np data:
data3 = data1.data * data2.data
Although this works for my need, I am still curious to understand why the pure xarray method fails. Can anyone inform me or point me towards a part of the documentation I might have missed?
For those interested, there was a slight difference in the coordinates of my two data arrays, apparently due to floating point precision (thanks to these guys). You can check whether coordinates of both data arrays are correct with:
import xarray as xr
xr.testing.assert_equal(data1.lon, data2.lon)
xr.testing.assert_equal(data1.lat, data2.lat)
In case one is sure the coordinates should align, one option is to manually correct the coordinates:
data1['lon'] = data2['lon']
data1['lat'] = data2['lat']
Then the multiplication works without problem.