What is the best way to add a new element at the start of numpy array and delete the last element of this array ?
I used code like this :
tmp = np.array([1,2,3])
print(tmp)
tmp = np.insert(tmp,0,0)
tmp = np.delete(tmp,-1)
print(tmp)
So I got what I wanted:
[1 2 3]
[0 1 2]
But I suspect that there is a better way to do this.
A cleaner way to do what you are doing:
tmp = np.insert(tmp[0:-1], 0, 0)
or
tmp = np.append([0], tmp[0:-1])
or
tmp = np.concatenate(([0], tmp[0:-1]))
If you want to insert at a specific position in the array then .insert
is clean approach but if your requirements are to add an element at 0th position(or end) then concatenate might be more efficient.
A simple timeit check reveals 2.07 µs
per loop for concatenate, 5.47 µs
per loop for append and 12.7
µs per loop for insert(this is not the perfect way of measuring time but it gives a rough estimate)
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