Input Array: Output Array:
[[1,2,3], [[1,2,3,3,3],
[0,0,0], -> repeat(2-times) -> [0,0,0,0,0],
[0,2,1]] [0,2,1,1,1]]
x = np.array([[1,2,3],[0,0,0],[0,2,1]])
# to repeat last row two times two times
new_size = x.shape[1] + 2
new_x = np.zeros((3,new_size))
new_x[:,:3] = x
for i in range(x.shape[1],new_size):
new_x[:,i] = x[:,-1]
The numpy.repeat() function repeats elements of the array – arr. Syntax : numpy.repeat(arr, repetitions, axis = None) Parameters : array : [array_like]Input array. repetitions : No. of repetitions of each array elements along the given axis. axis : Axis along which we want to repeat values. By default, it returns a flat output array.
You can use slicing to get the last N columns of a 2D array in Numpy. Here, we use column indices to specify the range of columns we’d like to slice. To get the last n columns, use the following slicing syntax – It returns the array’s last n columns (including all the rows).
Keep in mind that although the np.repeat function is primarily designed to operate on NumPy arrays, it will also work on any array-like object. That includes Python lists and Python tuples. Technically, it will even operate on a string (although it will treat it like a Python list).
When we use the axis parameter, we are specifying the direction along which we will repeat the items. So for example, if we have a 2-dimensional NumPy array and we want to repeat the items downwards down the columns, we will set axis = 0. If we want to repeat the items horizontally across the rows, we will set axis = 1.
One possible solution:
a = np.hstack((arr, np.tile(arr[:, [-1]], 2)))
print (a)
[[1 2 3 3 3]
[0 0 0 0 0]
[0 2 1 1 1]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With