Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add element at the start of array and delete at the end numpy

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.

like image 333
PhilNox Avatar asked Nov 27 '17 18:11

PhilNox


1 Answers

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)

like image 176
Amit Tripathi Avatar answered Sep 26 '22 00:09

Amit Tripathi