Duncan WP
Duncan WP

Reputation: 880

Combining DataArrays in an xarray Dataset

Is there a nicer way of summing over all the DataArrays in an xarray Dataset than

sum(d for d in ds.data_vars.values())

This works, but seems a bit clunky. Is there an equivalent to summing over pandas DataFrame columns?

Note the ds.sum() method applies to each of the DataArrays - but I want to combine the DataArrays.

Upvotes: 3

Views: 1411

Answers (1)

shoyer
shoyer

Reputation: 9593

I assume you want to sum each data variable as well, e.g., sum(d.sum() for d in ds.data_vars.values()). In a future version of xarray (not yet in v0.10) this will be more succinct: you will be able to write sum(d.sum() for d in ds.values()).

Another option is to convert the Dataset into a single DataArray and sum it at once, e.g., ds.to_array().sum(). This will be less efficient if you have data variables with different dimensions.

Upvotes: 5

Related Questions