Skip to content

Taking the diagonal of each 2-D array along a third dimension? Current approach uses deprecated groupby-squeeze #9173

Answered by keewis
claytharrison asked this question in Q&A
Discussion options

You must be logged in to vote

If I understand correctly, the groupby is supposed to work around the fact that diag doesn't take an axis parameter. If so, try this:

def extract_variances(arr, dims=None, new_dim="cov"):
    if dims is None:
        dims = ["cov_i", "cov_j"]
    cov_size = min(size for name, size in arr.sizes.items() if name in dims)
    return xr.apply_ufunc(
        np.diag,
        arr,
        input_core_dims=[dims],
        output_core_dims=[[new_dim]],
        vectorize=True,
        dask="parallelized",
        dask_gufunc_kwargs={"output_sizes": {"cov": cov_size}},
    )

arr = xr.DataArray([[[1, 0], [0, 1]], [[4, 0], [0, 4]]], dims=["dim0", "cov_i", "cov_j"])
np.sqrt(extract_variances(arr))
np.sqrt

Replies: 1 comment 4 replies

Comment options

You must be logged in to vote
4 replies
@claytharrison
Comment options

@keewis
Comment options

@dcherian
Comment options

@claytharrison
Comment options

Answer selected by claytharrison
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants