Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeat last column in numpy array

Problem

I am trying to repeat the last column in a Numpy array. Is there a more "elegant" way than resizing the array, copying the values and repeating the last row x times?

What I want to achieve

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]]

How I solved the problem

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]

Other way

Is there a way to solve this problem with the numpy repeat function? Or something shorter or more efficient?
like image 218
clfaster Avatar asked Feb 15 '18 10:02

clfaster


People also ask

How to repeat elements of an array in NumPy?

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.

How to get last n columns of a 2D array in NumPy?

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).

Does NumPy repeat work on tuples?

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).

What is the Axis parameter in NumPy?

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.


1 Answers

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]]
like image 75
jezrael Avatar answered Sep 28 '22 02:09

jezrael