Adam Adam - 1 month ago 4
Python Question

append element to the end of each arrow in numpy array

If i have an numpy array like:

x= [[3, 3], [2, 2]]


I want to add an element -1 to the end of each arrow to be like this:

x= [[3, 3, -1], [2, 2, -1]]


any simple way to do that ?

Answer

A simple way would be with np.insert -

np.insert(x,x.shape[1],-1,axis=1)

We can also use np.column_stack -

np.column_stack((x,[-1]*x.shape[0]))

Sample run -

In [161]: x
Out[161]: 
array([[0, 8, 7, 0, 1],
       [0, 1, 8, 6, 8],
       [3, 4, 7, 0, 2]])

In [162]: np.insert(x,x.shape[1],-1,axis=1)
Out[162]: 
array([[ 0,  8,  7,  0,  1, -1],
       [ 0,  1,  8,  6,  8, -1],
       [ 3,  4,  7,  0,  2, -1]])

In [163]: np.column_stack((x,[-1]*x.shape[0]))
Out[163]: 
array([[ 0,  8,  7,  0,  1, -1],
       [ 0,  1,  8,  6,  8, -1],
       [ 3,  4,  7,  0,  2, -1]])
Comments