How to make a list of numpy arrays, all have the same shape?

So, I have a set of 2d Numpy arrays in the 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 is changing.

Let's say that the shape of the array is X (n, m) and the shape of the array is Y (n + 2, m). I would like to add two strings of zeros to the array X, so that X and Y are both (n + 2, m).

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

Thank you all!

+4
source share
2 answers

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)]) 
+4
source

Relatively recently, numpy.pad was introduced, so also:

 >>> X = np.ones((3,2)) >>> Y = np.ones((5,2))*2 >>> N = 5 >>> nX, nY = [np.pad(m, ((0,Nm.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.]]) 
+2
source

Source: https://habr.com/ru/post/1483501/


All Articles