0

I have a 2D NumPy array and I hope to expand its size on both dimensions by copying the bottom row and right column.

For example, from 2x2:

[[0,1],
 [2,3]]

to 4x4:

[[0,1,1,1],
 [2,3,3,3],
 [2,3,3,3],
 [2,3,3,3]]

What's the best way to do it?

Thanks.

2 Answers 2

3

Here, the hstack and vstack functions can come in handy. For example,

In [16]: p = array(([0,1], [2,3]))
In [20]: vstack((p, p[-1], p[-1]))
Out[20]:
    array([[0, 1],
           [2, 3],
           [2, 3],
           [2, 3]])

And remembering that p.T is the transpose:

So now you can do something like the following:

In [16]: p = array(([0,1], [2,3]))
In [22]: p = vstack((p, p[-1], p[-1]))
In [25]: p = vstack((p.T, p.T[-1], p.T[-1])).T
In [26]: p
Out[26]:
array([[0, 1, 1, 1],
       [2, 3, 3, 3],
       [2, 3, 3, 3],
       [2, 3, 3, 3]])

So the 2 lines of code should do it...

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

1 Comment

I have tried it. it works much better than my naive for loop copy for each column/row. Thanks
1

Make an empty array and copy whatever rows, columns you want into it.

def expand(a, new_shape):
    x, y = a.shape
    r = np.empty(new_shape, a.dtype)
    r[:x, :y] = a
    r[x:, :y] = a[-1:, :]
    r[:x, y:] = a[:, -1:]
    r[x:, y:] = a[-1, -1]
    return r

1 Comment

Cool. I like this function. it works for generic 2-D array size.

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.