Code works fine with xarray version 0.17.0 but not in version 2022.11.0


This code works in version ‘0.17.0’, but not in version ‘2022.11.0’. The error is:

/home/alexandre/miniconda3/envs/grade_2020_3/bin/python /home/alexandre/Dropbox/grade_2020/examples/ 
Traceback (most recent call last):
  File "/home/alexandre/Dropbox/grade_2020/examples/", line 14, in <module>
    prec.coords['mask'] = (('latitude', 'longitude'), mask_array)
  File "/home/alexandre/miniconda3/envs/grade_2020_3/lib/python3.8/site-packages/xarray/core/", line 32, in __setitem__
    self.update({key: value})
  File "/home/alexandre/miniconda3/envs/grade_2020_3/lib/python3.8/site-packages/xarray/core/", line 162, in update
    coords, indexes = merge_coords(
  File "/home/alexandre/miniconda3/envs/grade_2020_3/lib/python3.8/site-packages/xarray/core/", line 564, in merge_coords
    collected = collect_variables_and_indexes(aligned)
  File "/home/alexandre/miniconda3/envs/grade_2020_3/lib/python3.8/site-packages/xarray/core/", line 365, in collect_variables_and_indexes
    variable = as_variable(variable, name=name)
  File "/home/alexandre/miniconda3/envs/grade_2020_3/lib/python3.8/site-packages/xarray/core/", line 126, in as_variable
    raise TypeError(
TypeError: Using a DataArray object to construct a variable is ambiguous, please extract the data using the .data property.

Process finished with exit code 1

The line "prec.coords[‘mask’] = ((‘latitude’, ‘longitude’), mask_array)" must be rewrite but I can’t found how do it. I appreciate help.


import xarray as xr
import numpy as np

# netcdf file from:
path_var = '/home/alexandre/Dropbox/grade_2020/data/netcdf_files/'
prec = xr.open_mfdataset(path_var + '')

# mask ocean and land
mask_ocean = 2 * np.ones(prec['pr'].shape[1:]) * np.isnan(prec['pr'].isel(time=0))
mask_land = 1 * np.ones(prec['pr'].shape[1:]) * ~np.isnan(prec['pr'].isel(time=0))
mask_array = mask_ocean + mask_land

# mask in prec
prec.coords['mask'] = (('latitude', 'longitude'), mask_array)
Asked By: Alexandre



You are attempting to use an outdated shortcut to construct a DataArray. Instead, use the DataArray constructor directly:

prec.coords['mask'] = xr.DataArray(mask_array, dims=('latitude', 'longitude'))
Answered By: jhamman
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.