Stream: python-questions

Topic: xarray reverse cumsum?


view this post on Zulip Stephen Yeager (Apr 18 2022 at 14:58):

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.

view this post on Zulip Stephen Yeager (Apr 18 2022 at 15:08):

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))

view this post on Zulip Deepak Cherian (Apr 18 2022 at 15:22):

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

view this post on Zulip Deepak Cherian (Apr 18 2022 at 15:22):

There's similar discussion at xgcm: https://github.com/xgcm/xgcm/issues/337

view this post on Zulip Matt Long (Apr 19 2022 at 12:28):

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.

view this post on Zulip Stephen Yeager (Apr 19 2022 at 16:23):

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