Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add single element to array in numpy

People also ask

How do I add one element to a NumPy array?

Use append() to add an element to Numpy Array. Use concatenate() to add an element to Numpy Array. Use insert() to add an element to Numpy Array.

Can you append to a NumPy array?

append() is used to append values to the end of an array. It takes in the following arguments: arr : values are attached to a copy of this array.


append() creates a new array which can be the old array with the appended element.

I think it's more normal to use the proper method for adding an element:

a = numpy.append(a, a[0])

When appending only once or once every now and again, using np.append on your array should be fine. The drawback of this approach is that memory is allocated for a completely new array every time it is called. When growing an array for a significant amount of samples it would be better to either pre-allocate the array (if the total size is known) or to append to a list and convert to an array afterward.

Using np.append:

b = np.array([0])
for k in range(int(10e4)):
    b = np.append(b, k)
1.2 s ± 16.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Using python list converting to array afterward:

d = [0]
for k in range(int(10e4)):
    d.append(k)
f = np.array(d)
13.5 ms ± 277 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Pre-allocating numpy array:

e = np.zeros((n,))
for k in range(n):
    e[k] = k
9.92 ms ± 752 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

When the final size is unkown pre-allocating is difficult, I tried pre-allocating in chunks of 50 but it did not come close to using a list.

85.1 ms ± 561 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

a[0] isn't an array, it's the first element of a and therefore has no dimensions.

Try using a[0:1] instead, which will return the first element of a inside a single item array.


Try this:

np.concatenate((a, np.array([a[0]])))

http://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html

concatenate needs both elements to be numpy arrays; however, a[0] is not an array. That is why it does not work.


This command,

numpy.append(a, a[0])

does not alter a array. However, it returns a new modified array. So, if a modification is required, then the following must be used.

a = numpy.append(a, a[0])

t = np.array([2, 3])
t = np.append(t, [4])