Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to "spread" a numpy array (opposite of slice with step size)?

Is there a way to spread the values of a numpy array? Like an opposite to slicing with a step size > 1:

>>> a = np.array([[1, 0, 2], [0, 0, 0], [3, 0, 4]])
>>> a
array([[1, 0, 2],
       [0, 0, 0],
       [3, 0, 4]])

>>> b = a[::2, ::2]
>>> b
array([[1, 2],
       [3, 4]])

In this example, is there an elegant way to get a from b?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can create a zeros array with correct shape first and then assign with step size:

import numpy as np
b = np.array([[1, 2], [3, 4]])
a = np.zeros((b.shape[0] * 2 - 1, b.shape[1] * 2 - 1), dtype='int')
a[::2, ::2] = b
a
# array([[1, 0, 2],
#        [0, 0, 0],
#        [3, 0, 4]])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading