Beardsley
Beardsley

Reputation: 171

Mean of every n slices in 3d array - python

I have a 3d array that represents hourly data over the course of a 30 day month. It's shape is 720x13x85 (there are 720 hours in 30 days). I want to take the mean of every 24 hours, or 24 slices, so that I have daily data. This seems like a simple problem but I haven't found a way, or any answers to this exact problem elsewhere in the forum. I found this related question with no answer.

i.e. I want to get the following, and calculate mean for each day

Day1precip = precip[0:24,:,:]

and so on for a month. Ideally I want the result in a 3d-array, so that newarray[0,:,:] is day1 and so on.

Upvotes: 1

Views: 461

Answers (2)

Athul Nair
Athul Nair

Reputation: 1

Here's a simple way to think about what you are trying to do.

Instead of having 720 hours, you wish to have 30 days of data. To achieve that, you have to average every group of consecutive 24 hours. Each averaged 24 hours becomes 1 day.

Therefore, you can think of your 720 hours to be put into 30 groups of 24 hours. (720 = 30 x 24)

Your shape goes from (720, 13, 85) to (30, 24, 13, 85). In other words, now you have 30 days, each with 24 hours, and each hour having data with dimensions (13, 85). Now when you average the 24 hours within each group, you get a dataset with the shape (30, 13, 85), that you are looking for.

In code, it looks like:

result = precip.reshape(30, 24, 13, 85).mean(1)

This is what Mad Physicist was essentially saying, but I find it easier to understand this way.

Upvotes: 0

Mad Physicist
Mad Physicist

Reputation: 114330

Add a new dimension, then take the mean of that:

precip.reshape(-1, 24, *precip.shape[1:]).mean(1)

Later dimensions are always more contiguous for reshape. That means that splitting the first dimension into 30, 24 makes for 30 blocks of 24 elements each, not the other way around.

Upvotes: 1

Related Questions