Add one element to an array in numpy

I have a numpy array containing:

[1, 2, 3] 

I want to create an array containing:

 [1, 2, 3, 1] 

That is, I want to add the first element to the end of the array.

I tried the obvious:

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

But I get the error ValueError: arrays must have same number of dimensions

I don’t understand this - arrays are just 1d arrays.

+43
python arrays numpy
Sep 07 2018-11-11T00:
source share
7 answers

I think it is more normal to use the correct method to add an element:

 numpy.append(a, a[0]) 
+69
Sep 07 '11 at 11:21
source share

a[0] not an array, it is 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 array of elements.

+10
07 Sep '11 at 11:12
source share

try it

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

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

concatenate requires both elements to be an array, however [0] is not an array. That is why it does not work.

+7
Sep 07 '11 at 11:15
source share
 t = np.array([2, 3]) t = np.append(t, [4]) 
+3
Sep 22 '13 at 17:28
source share

This may be a little redundant, but I always use the np.take function for any indexing of the wrapper:

 >>> a = np.array([1, 2, 3]) >>> np.take(a, range(0, len(a)+1), mode='wrap') array([1, 2, 3, 1]) >>> np.take(a, range(-1, len(a)+1), mode='wrap') array([3, 1, 2, 3, 1]) 
+3
Jan 25 '16 at 15:29
source share

Say a=[1,2,3] and you want it to be [1,2,3,1] .

You can use the built-in add function

 np.append(a,1) 

Here 1 is an int, it can be a string, and it may or may not belong to the elements in the array. Print: [1,2,3,1]

0
Jul 26 '17 at 0:59
source share

This team

numpy.append(a, a[0])

does not modify array a . However, it returns a new modified array. So, if modification a is required, then

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

.

0
Oct. 16 '17 at 15:28
source share



All Articles