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

Question:

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/teste_lixo.py 
Traceback (most recent call last):
  File "/home/alexandre/Dropbox/grade_2020/examples/teste_lixo.py", 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/coordinates.py", line 32, in __setitem__
    self.update({key: value})
  File "/home/alexandre/miniconda3/envs/grade_2020_3/lib/python3.8/site-packages/xarray/core/coordinates.py", line 162, in update
    coords, indexes = merge_coords(
  File "/home/alexandre/miniconda3/envs/grade_2020_3/lib/python3.8/site-packages/xarray/core/merge.py", 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/merge.py", 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/variable.py", 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.

Thanks.

import xarray as xr
import numpy as np

# netcdf file from: https://drive.google.com/drive/u/1/folders/11-qnvwojirAtaQxSE03N0_SUrbcsz44N
path_var = '/home/alexandre/Dropbox/grade_2020/data/netcdf_files/'
prec = xr.open_mfdataset(path_var + 'pr_19610101_19801231_BR-DWGD_UFES_UTEXAS_v_3.0.nc')

# 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

||

Answers:

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.