John Crow John Crow - 20 days ago 6
Python Question

What is the opposite of numpy.repeat?

The answer given here explains how to resize an array from

[1,5,9]
[2,7,3]
[8,4,6]


to

[1,1,5,5,9,9]
[1,1,5,5,9,9]
[2,2,7,7,3,3]
[2,2,7,7,3,3]
[8,8,4,4,6,6]
[8,8,4,4,6,6]


using
np.repeat
. Given the lower array, what is the best way to shrink it to the upper?

Answer

Slice across both axes with appropriate stepsize -

a[::2,::2] # 2 being stepsize here

Sample run -

In [23]: a
Out[23]: 
array([[1, 1, 5, 5, 9, 9],
       [1, 1, 5, 5, 9, 9],
       [2, 2, 7, 7, 3, 3],
       [2, 2, 7, 7, 3, 3],
       [8, 8, 4, 4, 6, 6],
       [8, 8, 4, 4, 6, 6]])

In [24]: a[::2,::2]
Out[24]: 
array([[1, 5, 9],
       [2, 7, 3],
       [8, 4, 6]])
Comments