Skip to content
Advertisement

Remove and add values to ​numpy array

Is there a more efficient way to remove the 0 from the beginning and insert the 20 at the end and retain the shape (1, 20)?

# What I have.
array = np.arange(20)[np.newaxis]
print(array.shape, array)

# Remove 0 from the beginning and add 20 to the end.
array = np.append(array[0, 1:], np.array([[20]]))
print(array)
array = array[np.newaxis]
print(array.shape, array)

Output:

(1, 20) [[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19]]
[ 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20]
(1, 20) [[ 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20]]

Advertisement

Answer

You can just select a subset of the current array excluding the first element and then add 20 or whatever scalar you want at the end.

x = np.append(array[:,1:],[[20]], axis=1)
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement