html_url,issue_url,id,node_id,user,created_at,updated_at,author_association,body,reactions,performed_via_github_app,issue https://github.com/pydata/xarray/issues/1772#issuecomment-791379121,https://api.github.com/repos/pydata/xarray/issues/1772,791379121,MDEyOklzc3VlQ29tbWVudDc5MTM3OTEyMQ==,1119116,2021-03-05T12:08:17Z,2021-03-05T12:09:32Z,NONE,"A possible code for this functionality could be: ``` def nonzero4xarray (da:xarray.DataArray): c = da.where(da, drop=True).coords s = da.sel(c).to_series() s = s[s] o = [] for record in s.index: o.append(dict(list(zip(s.index.names, record)))) return o ``` however the output is sub-optimal, as it yields a list of dicts, each with the corresponding coordinate to the nonzero value. Consider the following example: ``` >>> import numpy as np >>> import xarray as xr >>> x = np.arange(5) * 100 >>> y = np.arange(4) * 100 >>> z = np.arange(3) * 10 >>> da = xr.DataArray(np.random.randn(z.size, y.size, x.size), dims=('z', 'y', 'x'), coords={'x': x, 'y': y, 'z': z}) >>> da.loc[da.isel({'x':[0, 2], 'y':[1,3], 'z':[0]}).coords] = np.nan >>> da.loc[da.isel({'x':[1, 3], 'y':[0], 'z':[-1]}).coords] = np.nan ``` and imagine I want to capture the locations with NaN values. If I do: ``` >>> coords = da.where(da.isnull(), drop=True).coords >>> da.sel(coords) array([[[ 1.586261, -0.2003 , 0.734872, -1.198746], [ nan, -0.108265, nan, 0.754857], [ nan, 0.700742, nan, -1.514642]], [[ 1.109573, nan, -1.596756, nan], [ 0.031771, -0.341263, 1.358767, 0.221174], [-0.671605, 0.923703, 0.085335, -1.672686]]]) ``` I will get the coordinates for a mix of NaN and valid values, depending on how these are distributed. If I want to obtain only the NaN locations: ``` >>> coords = nonzero4xarray(da.isnull()) >>> coords [{'z': 0, 'y': 100, 'x': 0}, {'z': 0, 'y': 100, 'x': 200}, {'z': 0, 'y': 300, 'x': 0}, {'z': 0, 'y': 300, 'x': 200}, {'z': 20, 'y': 0, 'x': 100}, {'z': 20, 'y': 0, 'x': 300}] >>> vals = [da.sel(c).values[()] for c in coords] >>> vals [nan, nan, nan, nan, nan, nan] ``` whose functionality is similar to `numpy.nonzero`, although sub-optimal as we cannot issue `da.sel(coords)` directly.","{""total_count"": 0, ""+1"": 0, ""-1"": 0, ""laugh"": 0, ""hooray"": 0, ""confused"": 0, ""heart"": 0, ""rocket"": 0, ""eyes"": 0}",,280875330