Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prepend element to numpy array

I have the following numpy array

import numpy as np  X = np.array([[5.], [4.], [3.], [2.], [1.]]) 

I want to insert [6.] at the beginning. I've tried:

X = X.insert(X, 0) 

how do I insert into X?

like image 841
piRSquared Avatar asked May 03 '16 07:05

piRSquared


People also ask

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.

How do I append at the end of NumPy?

NumPy: append() functionThe append() function is used to append values to the end of an given array. Values are appended to a copy of this array. These values are appended to a copy of arr. It must be of the correct shape (the same shape as arr, excluding axis).

How do you push an element to an array in Python?

If you are using List as an array, you can use its append(), insert(), and extend() functions. You can read more about it at Python add to List. If you are using array module, you can use the concatenation using the + operator, append(), insert(), and extend() functions to add elements to the array.


1 Answers

numpy has an insert function that's accesible via np.insert with documentation.

You'll want to use it in this case like so:

X = np.insert(X, 0, 6., axis=0) 

the first argument X specifies the object to be inserted into.

The second argument 0 specifies where.

The third argument 6. specifies what is to be inserted.

The fourth argument axis=0 specifies that the insertion should happen at position 0 for every column. We could've chosen rows but your X is a columns vector, so I figured we'd stay consistent.

like image 137
Rosey Avatar answered Sep 20 '22 17:09

Rosey