The multiplication in xarray

Viewed 1079

We konw that xarray handle data by labels. That is, adding two datasets or multiplying two datasets are operated under the same dimensions and coordinates. However, I have a problem about the shape of the result after xarray multiplication operation.

The code is shown as follow:

import xarray as xr
import numpy as np
a = xr.DataArray([0,1,2,3],dims=['x'],
                 coords={'x':[10,20,30,40]})
b = xr.DataArray(np.array([[0,1,2,3],[0,100,200,300]]),
                 dims=['y','x'],
                 coords={'y':['y1','y2'],'x':[10,20,30,40]})
print(a*b)
print(b*a)

The first result is

<xarray.DataArray (x: 4, y: 2)>
array([[  0,   0],
       [  1, 100],
       [  4, 400],
       [  9, 900]])
Coordinates:
  * x        (x) int64 10 20 30 40
  * y        (y) <U2 'y1' 'y2'

The second result is

<xarray.DataArray (y: 2, x: 4)>
array([[  0,   1,   4,   9],
       [  0, 100, 400, 900]])
Coordinates:
  * y        (y) <U2 'y1' 'y2'
  * x        (x) int64 10 20 30 40

Actually, the first and second is equal because xarray is label-based, however, why the shape of first result is [4,2] and the second is [2,4]? Anyone who can tell me? Thanks!

1 Answers

(a*b.T) and (b.T*a) both produce arrays with shape [4,2]

I believe this is because b.T changes the DataArray dimension order in b but not the Coordinate order.

Compare b with b.T:

print(b)
<xarray.DataArray (y: 2, x: 4)>
array([[  0,   1,   2,   3],
       [  0, 100, 200, 300]])
Coordinates:
  * y        (y) <U2 'y1' 'y2'
  * x        (x) int64 10 20 30 40
print(b.T)
<xarray.DataArray (x: 4, y: 2)>
array([[  0,   0],
       [  1, 100],
       [  2, 200],
       [  3, 300]])
Coordinates:
  * y        (y) <U2 'y1' 'y2'
  * x        (x) int64 10 20 30 40
Related