pydata / pydata/xarray

`Dataset.broadcast_like(other)` should broadcast against like variables in other

Open
#6,549 7 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

enhancement
Dominant language
Python
Stars
4.2k
Forks
1.4k
Avg merge
2d 15h
Merged PRs (30d)
14

Description

Is your feature request related to a problem?

I am a bit puzzled about how xarrays is broadcasting Datasets.
It seems to always add all dimensions to all variables.
Is this what you want in general?

See this example:

import xarray as xr

da = xr.DataArray([[1, 2, 3]], dims=("x", "y"))
# <xarray.DataArray (x: 1, y: 3)>
# array([[1, 2, 3]])
ds = xr.Dataset({"a": ("x", [1]), "b": ("z", [2, 3])})
# <xarray.Dataset>
# Dimensions:  (x: 1, z: 2)
# Dimensions without coordinates: x, z
# Data variables:
#     a        (x) int32 1
#     b        (z) int32 2 3
ds.broadcast_like(da)

# returns:
# <xarray.Dataset>
# Dimensions:  (x: 1, y: 3, z: 2)
# Dimensions without coordinates: x, y, z
# Data variables:
#     a        (x, y, z) int32 1 1 1 1 1 1
#     b        (x, y, z) int32 2 3 2 3 2 3

# I think it should return:
# <xarray.Dataset>
# Dimensions:  (x: 1, y: 3, z: 2)
# Dimensions without coordinates: x, y, z
# Data variables:
#     a        (x, y) int32 1 1 1  # notice here without "z" dim
#     b        (x, y, z) int32 2 3 2 3 2 3
Describe the solution you'd like

I would like broadcasting to behave the same way as e.g. a simple addition.
In the upper example da + ds produces the dimensions that I want.

Describe alternatives you've considered

ds + xr.zeros_like(da) this works, but seems more like a "dirty hack".

Additional context

Maybe one can add an option to broadcasting that controls this behavior?

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at Dataset.broadcast_like and compare its behavior with the DataArray-plus-Dataset example in the issue. Determine whether broadcasting should follow each variable's existing dimensions; done when the example preserves a's lack of z while b includes x, y, and z, with regression coverage for the behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
data
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.