3

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.

1
  • 1
    Will axis 1 be always divisible by C? Commented Dec 24, 2019 at 21:19

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Elegant solution :) But unfortunately, wouldn't work if A.shape[1]%0 != 0. Not sure if this is a requirement of OP but just pointing out.
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.