0

I have two arrays, a and b.

a has shape (1, 2, 3, 4)

b has shape (4, 3, 2, 1)

I would like to make them both (4, 3, 3, 4) with the new positions filled with 0's.

I can do:

new_shape = (4, 3, 3, 4)

a = np.resize(a, new_shape)
b = np.resize(b, new_shape)

..but this repeats the elements of each to form the new elements, which does not work for me.

Instead I thought I could do:

a = a.resize(new_shape)
b = b.resize(new_shape)

..which according to the documentation pads with 0's.

But it doesn't work for multi-dimensional arrays, raising error:

ValueError: resize only works on single-segment arrays

So is there a different way to achieve this? ie. same as np.resize but with 0-padding?

NB: I am only looking for pure-numpy solutions.

EDIT: I'm using numpy version 1.20.2

EDIT: I just found out that is works for numbers, but not for objects, I forgot to mention that it is an array of objects not numbers.

6
  • 1
    a.resize(4,3,3,4, refcheck=False)? See the different documentations numpy.ndarray.resize and numpy.resize Commented Jul 7, 2021 at 17:40
  • @not_speshal no produces same error Commented Jul 7, 2021 at 17:56
  • Definitely works for me (numpy v1.20.2). Check your numpy version. Commented Jul 7, 2021 at 17:57
  • @not_speshal 1.20.2, definitely does not work for me. Commented Jul 7, 2021 at 17:59
  • @MustafaAydın Not on my pc, just upgraded, I have no idea why Commented Jul 7, 2021 at 18:02

1 Answer 1

0

resize method pads with 0s in a flattened sense; the function pads with repeats.

To illustrate how resize "flattens" before padding:

In [108]: a = np.arange(12).reshape(1,4,3)
In [109]: a
Out[109]: 
array([[[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8],
        [ 9, 10, 11]]])
In [110]: a1 = a.copy()
In [111]: a1.resize((2,4,4))
In [112]: a1
Out[112]: 
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11],
        [ 0,  0,  0,  0]],

       [[ 0,  0,  0,  0],
        [ 0,  0,  0,  0],
        [ 0,  0,  0,  0],
        [ 0,  0,  0,  0]]])

If instead I make a target array of the right shape, and copy, I can maintain the original multidimensional block:

In [114]: res = np.zeros((2,4,4),a.dtype)
In [115]: res[:a.shape[0],:a.shape[1],:a.shape[2]]=a
In [116]: res
Out[116]: 
array([[[ 0,  1,  2,  0],
        [ 3,  4,  5,  0],
        [ 6,  7,  8,  0],
        [ 9, 10, 11,  0]],

       [[ 0,  0,  0,  0],
        [ 0,  0,  0,  0],
        [ 0,  0,  0,  0],
        [ 0,  0,  0,  0]]])

I wrote out the slices explicitly (for clarity). Such a tuple could be created programmatically if needed.

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

Comments

Your Answer

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