I have an 2d array, A that is 6×6. I would like to take the first 2 values (index 0,0 and 0,1) and take the average of the two and insert the average into a new array that is half the column size of A (6×3) at index 0,0. Then i would get the next two indexes at A, take average and put into the new array at 0,1.
The only way I know how to do this is using a double for loop, but for performance purposes (I will be using arrays as big as 3000×3000) I know there is a better solution out there! Thanks!
A very useful feature of numpy arrays is that they can be reshaped and viewed in many different ways, and by doing so, you can make certain operations very easy.
Since you want to pair every two items, it makes sense to reshape the 6×6 array into a 18×2 array:
Now taking the average is easy:
And finally, we just reshape the array to be 6×3:
or, as a 1-liner:
PS: reshaping is a very quick operation, since it is returning a view, not a copy of the original array. All that is changed is the dimensions and the strides. All that remains is one call to the
meanmethod. Thus, this solution should be about a quick as possible using numpy.