Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert element into numpy array

Tags:

Lists have a very simple method to insert elements:

a = [1,2,3,4]
a.insert(2,66)
print a
[1, 2, 66, 3, 4]

For a numpy array I could do:

a = np.asarray([1,2,3,4])
a_l = a.tolist()
a_l.insert(2,66)
a = np.asarray(a_l)
print a
[1 2 66 3 4]

but this is very convoluted.

Is there an insert equivalent for numpy arrays?

like image 390
Gabriel Avatar asked Feb 13 '14 17:02

Gabriel


People also ask

How do you add an element to an array in python?

If you are using List as an array, you can use its append(), insert(), and extend() functions. You can read more about it at Python add to List. If you are using array module, you can use the concatenation using the + operator, append(), insert(), and extend() functions to add elements to the array.

Can you use append on NumPy array?

A NumPy array does not have a built-in append method. Instead, to append elements to a NumPy array, use a separate numpy. append() function.


2 Answers

You can use numpy.insert, though unlike list.insert it returns a new array because arrays in NumPy have fixed size.

>>> import numpy as np
>>> a = np.asarray([1,2,3,4])
>>> np.insert(a, 2, 66)
array([ 1,  2, 66,  3,  4])
like image 135
Ashwini Chaudhary Avatar answered Sep 22 '22 02:09

Ashwini Chaudhary


If you just want to insert items in consequent indices, as a more optimized way you can use np.concatenate() to concatenate slices of the array with your intended items:

For example in this case you can do:

In [21]: np.concatenate((a[:2], [66], a[2:]))
Out[21]: array([ 1,  2, 66,  3,  4])

Benchmark (5 time faster than insert ):

In [19]: %timeit np.concatenate((a[:2], [66], a[2:]))
1000000 loops, best of 3: 1.43 us per loop

In [20]: %timeit np.insert(a, 2, 66)
100000 loops, best of 3: 6.86 us per loop

And here is a benchmark with larger arrays (still 5 time faster):

In [22]: a = np.arange(1000)

In [23]: %timeit np.concatenate((a[:300], [66], a[300:]))
1000000 loops, best of 3: 1.73 us per loop                                              

In [24]: %timeit np.insert(a, 300, 66)
100000 loops, best of 3: 7.72 us per loop
like image 19
Mazdak Avatar answered Sep 22 '22 02:09

Mazdak