Insert element into numpy array

Lists have a very easy way 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 it is very confusing.

Is there an insert equivalent for numpy arrays?

+8
source share
3 answers

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

 >>> import numpy as np >>> a = np.asarray([1,2,3,4]) >>> np.insert(a, 2, 66) array([ 1, 2, 66, 3, 4]) 
+13
source

If you just want to insert elements into subsequent indexes, as a more optimized way, you can use np.concatenate() to combine the fragments of the array with your intended elements:

For example, in this case you can:

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

Test (5 times 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 the standard with large arrays (another 5 times 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 
+6
source

To add elements to a numpy array, you can use the 'append' method, passing it the array and the element you want to add. For instance:

import numpy as np dummy = [] dummy = np.append(dummy,12)

this will create an empty array and add the number "12" to it

0
source

All Articles