The Python Oracle

Add single element to array in numpy

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Ominous Technology Looping

--

Chapters
00:00 Question
00:49 Accepted answer (Score 237)
01:08 Answer 2 (Score 48)
02:23 Answer 3 (Score 17)
02:47 Answer 4 (Score 16)
03:09 Thank you

--

Full question
https://stackoverflow.com/questions/7332...

Answer 2 links:
http://docs.scipy.org/doc/numpy/referenc...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #arrays #numpy

#avk47



ACCEPTED ANSWER

Score 264


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])



ANSWER 2

Score 18


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.




ANSWER 3

Score 16


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])



ANSWER 4

Score 15


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.