Home > Mobile >  How to append N number of an array to the end of another array
How to append N number of an array to the end of another array

Time:03-15

I have an array of size 99 columns by 100 rows but want to add the last row of the 2D array to the end of the array N times. My current code to do this is:

array = np.concatenate((l, np.tile(l[-1],n)))

where l is the array and n is the number of arrays I want to add on to it.

When I try to run this I get the error:

ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 2 dimension(s) and the array at index 1 has 1 dimension(s)

Any advice would be a massive help

CodePudding user response:

Use np.repeat with axis=1 and add an extra None indexer to l instead:

array = np.concatenate([l, np.repeat(l[-1, None], n, axis=0)])

CodePudding user response:

Did you test the tile before using it in this expression?

In [29]: l = np.ones((100, 99))
In [30]: l.shape
Out[30]: (100, 99)
In [31]: np.tile(l[-1], 3).shape
Out[31]: (297,)

l is 2d, right? What's the tile - 1d. Hence

ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 2 dimension(s) and the array at index 1 has 1 dimension(s)

Which don't you understand? Why the tile produced a 1d, or why concatenate complains about the dimensions?

Look at the l[-1]:

In [32]: l[-1].shape
Out[32]: (99,)

It is 1d; we can make it into a 1 row, 2d array with:

In [34]: l[-1][None,:].shape
Out[34]: (1, 99)

And into a 3 row array (tile should have a replication factor for each dimension):

In [36]: np.tile(l[-1][None,:], (3,1)).shape
Out[36]: (3, 99)

Now the concatenate works:

In [38]: np.concatenate((l,np.tile(l[-1][None, :], (3, 1)))).shape
Out[38]: (103, 99)

Another way of making the 2d array:

In [39]: l[[-1]].shape
Out[39]: (1, 99)
  • Related