Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient 2D array processing

Let A be a 2D matrix of size NxL. Every row A[i] should be processed independently such that all entries in consecutive chunks of length C in every row are replaced by the average value of the entries in the chunk. Specifically, I am looking for an efficient way to replace every k-th chunk in every i-th row A[i][kC:(k+1)C] by mean(A[i][kC:(k+1)C]) * ones(length=C).

Example

A=[[1,3,5,7], [7,5,3,1]] should be transformed to A=[[2,2,6,6],[6,6,2,2]] if C=2.

like image 715
Nocturne Avatar asked Dec 04 '25 00:12

Nocturne


1 Answers

You can reshape the data into chunks, take the mean and use broadcasting to assign the data back into the array

 B = A.reshape(-1, C)
 B[...] = B.mean(-1)[:, None]

Afterwards A contains the desired result as B is not a copy but a view.

like image 124
Nils Werner Avatar answered Dec 06 '25 12:12

Nils Werner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!