Reputation: 133
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
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
Reputation: 11333
Simply do
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)
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