4

So I have a bunch of 2d Numpy arrays in a list, and I want to make sure that they all have the same shape. I know that the second dimension is the same for each array, but the first dimension varies.

Say the shape of array X is (n,m) and the shape of array Y is (n+2,m). I would like to add two rows of zeros to array X so that X and Y are both (n+2,m).

What is the most Python-ic way to go through the list, making sure that all arrays have the same shape? Let's say I know what the largest value of the first dimension is for all arrays in the list - call it N - and, as I mentioned, I know that all arrays have a second dimension of m.

Thanks, everybody!

2 Answers 2

4

In one-line:

[np.r_[a, np.zeros((N - a.shape[0], m), dtype=a.dtype)] for a in your_arrays]

Probably more readable

for i,a in enumerate(your_arrays):
  rows, cols = a.shape
  if rows != N:
    your_arrays[i] = np.vstack([a, np.zeros((N - rows, cols), dtype=a.dtype)])
Sign up to request clarification or add additional context in comments.

1 Comment

That nailed it, and the code is nice, compact, and beautiful. Thanks, @wim!
2

Relatively recently, numpy.pad was introduced, so there's also:

>>> X = np.ones((3,2))
>>> Y = np.ones((5,2))*2
>>> N = 5
>>> nX, nY = [np.pad(m, ((0,N-m.shape[0]),(0,0)), 'constant') for m in [X, Y]]
>>> nX
array([[ 1.,  1.],
       [ 1.,  1.],
       [ 1.,  1.],
       [ 0.,  0.],
       [ 0.,  0.]])
>>> nY
array([[ 2.,  2.],
       [ 2.,  2.],
       [ 2.,  2.],
       [ 2.,  2.],
       [ 2.,  2.]])

Comments

Your Answer

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