The Python Oracle

Add single element to array in numpy

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Dreaming in Puzzles

--

Chapters
00:00 Add Single Element To Array In Numpy
00:25 Answer 1 Score 15
00:43 Answer 2 Score 18
01:03 Accepted Answer Score 264
01:18 Answer 4 Score 16
01:32 Thank you

--

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

--

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.