Home > Mobile >  np.insert() -1 as the position of an element
np.insert() -1 as the position of an element

Time:06-19

I am playing with the NumPy library and there is a behaviour that I do not understand:

I defined a simple vector Y:

Y = np.array([6,7,8],dtype = np.int16)

Then, I tried to add an additional element at the end of the array using the np.insert() method. I specified the position to be at -1:

Z = np.insert(Y,(-1),(19))

My element was inserted not on the last, but on the penultimate position:

Output

Could somebody explain my why this element was not inserted at the end of my array?

CodePudding user response:

Negative indexes are calculated using len(l) i (with l being the object and i being the negative index).

For example, with a list x = [1, 2, 3, 4] the index -2 is calculated as 4-2 = 2, so x[-2] returns 3

In this example, the index -1 is calculated as index 2

Therefore, 19 is inserted at index 2, the penultimate position. To fix this, use Z = np.insert(Y, len(Y), 19).

PS - this is the same with list.insert, not just with numpy arrays

Edit (suggested by Homer512): np.append may be easier than np.insert if you want to add to the end of an array: Z = np.append(Y, 19)

  • Related