calculate mean of 'n' number of rows

12 views
Skip to first unread message

Ranjan Kumar Sahu

unread,
Nov 16, 2022, 2:03:24 PM11/16/22
to xarray
hii all,
I am trying to calculate the average of n number of rows, for every subsequent rows, in such a way that,
avg1 = avg of 0 to n rows
avg2 = avg of n+1 to 2n rows

and so on.

In pandas, there is groupby function, wherein conditional statement can be incorporated, unlike the groupby function of xarray. (or maybe there is and I dont know yet)

Any ideas how I can achieve this.

any help is appreciated.
ranjan

Thomas Elliot Gruffydd Nicholas

unread,
Nov 16, 2022, 2:16:21 PM11/16/22
to xar...@googlegroups.com
Hi Ranjan,

Have you seen the coarsen method? I think you should be able to use something like  .coarsen(dim_name=n).mean() to achieve what you want.

Let us know if that works for you!

--
You received this message because you are subscribed to the Google Groups "xarray" group.
To unsubscribe from this group and stop receiving emails from it, send an email to xarray+un...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/xarray/19bbb2b4-92c2-48f0-b919-b446074d41f9n%40googlegroups.com.

Ranjan Kumar Sahu

unread,
Nov 16, 2022, 3:18:03 PM11/16/22
to xarray
hii ten,
Thanks for the response.
I have implemented the code. It works!! Without any errors!! But the thing is I expected the length of the dimension (in my case the depth dimension) to be halved compared to original length of the dimension.

        print(np.shape(ds2["Depth"]))
        >>> (58,)

        ds2.coarsen(Depth=2).mean()
        print(np.shape(ds2["Depth"]))
        >>> (58,)
regards
ranjan

Ranjan Kumar Sahu

unread,
Nov 16, 2022, 3:27:09 PM11/16/22
to xarray
I apologize. it works.
       ds2_m =  ds2.coarsen(Depth=2).mean()
storing it in a new variable solves the issue.

thanks for the help.

Thomas Elliot Gruffydd Nicholas

unread,
Nov 16, 2022, 3:40:19 PM11/16/22
to xar...@googlegroups.com
Isn't that just because you haven't assigned your result to a new variable? i.e.

>>> result = ds2.coarsen(Depth=2).mean()
>>> print(result["Depth"].shape)

(You also can use the .shape attribute instead of calling np.shape as I did here)


Reply all
Reply to author
Forward
0 new messages