Nocturne
Nocturne

Reputation: 133

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.

Upvotes: 3

Views: 79

Answers (2)

Nils Werner
Nils Werner

Reputation: 36729

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.

Upvotes: 2

thushv89
thushv89

Reputation: 11333

Simply do

If a.shape[1]%c==0

res = np.concatenate([np.repeat(a.mean(axis=1,keepdims=True),c, axis=1) for a in np.split(A, c, axis=1)], axis=1)

Else

res = np.concatenate(
    [np.repeat(a.mean(axis=1,keepdims=True),a.shape[1], axis=1) for a in np.split(A, list(range(0,A.shape[1],c)), axis=1)], axis=1)

Upvotes: 1

Related Questions