Is there a simply way to perform a reverse cumulative sum with xarray? For example, if I have an xarray dataarray foo with a 'depth' coordinate/dimension, then foo.cumsum('depth') will give me the top-down cumulative sum, but I want the bottom-up sum. I know how to reverse the dimension using "::-1" on the underlying numpy array, but I want to avoid hardcoding knowledge of the dimension location.
One clunky method is the following (is the best available method?):
foo_cumsum = foo.sel(depth=slice(None,None,-1)).cumsum('depth').sel(depth=slice(None,None,-1))
yes.
we could add a flag to cf_xarray. that lets you specify order. This would only work if depth
has attrs["positive"]
set to either up
or down
There's similar discussion at xgcm: https://github.com/xgcm/xgcm/issues/337
I think you can probably reverse the coordinate by specifying a "-1" stride in the indexing:
foo_cumsum = foo[:, ::-1, :, :].cumsum('depth')
Obviously, you need to know the index position.
Thanks both. Matt, yes but it's desirable not to have to hard-code assumptions about array dimensionality. Deepak, fixes using cf_xarray or xgcm are possible, but I would think this should be considered as an option for the cumsum method of xarray.
Last updated: May 16 2025 at 17:14 UTC