Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting a row at a specific location in a 2d array in numpy?

Tags:

python

numpy

I have a 2d array in numpy where I want to insert a new row. Following question Numpy - add row to array can help. We can use numpy.vstack, but it stacks at the start or at the end. Can anyone please help in this regard.

like image 1000
Shan Avatar asked Nov 28 '11 16:11

Shan


People also ask

How do I add a row to an array in NumPy?

Use the numpy. append() Function to Add a Row to a Matrix in NumPy. The append() function from the numpy module can add elements to the end of the array. By specifying the axis as 0, we can use this function to add rows to a matrix.

How do I assign a row in NumPy?

Rows and columns of NumPy arrays can be selected or modified using the square-bracket indexing notation in Python. To select a row in a 2D array, use P[i] . For example, P[0] will return the first row of P . To select a column, use P[:, i] .

How do I add one element to a NumPy array?

Use append() to add an element to Numpy Array. Use concatenate() to add an element to Numpy Array. Use insert() to add an element to Numpy Array.


1 Answers

You are probably looking for numpy.insert

>>> import numpy as np >>> a = np.zeros((2, 2)) >>> a array([[ 0.,  0.],        [ 0.,  0.]]) # In the following line 1 is the index before which to insert, 0 is the axis. >>> np.insert(a, 1, np.array((1, 1)), 0)   array([[ 0.,  0.],        [ 1.,  1.],        [ 0.,  0.]]) >>> np.insert(a, 1, np.array((1, 1)), 1) array([[ 0.,  1.,  0.],        [ 0.,  1.,  0.]]) 
like image 170
mac Avatar answered Sep 18 '22 15:09

mac