Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy - add row to array

How does one add rows to a numpy array?

I have an array A:

A = array([[0, 1, 2], [0, 2, 0]]) 

I wish to add rows to this array from another array X if the first element of each row in X meets a specific condition.

Numpy arrays do not have a method 'append' like that of lists, or so it seems.

If A and X were lists I would merely do:

for i in X:     if i[0] < 3:         A.append(i) 

Is there a numpythonic way to do the equivalent?

Thanks, S ;-)

like image 622
Darren J. Fitzpatrick Avatar asked Oct 07 '10 12:10

Darren J. Fitzpatrick


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 add rows to an empty NumPy array?

If we have an empty array and want to append new rows to it inside a loop, we can use the numpy. empty() function. Since no data type is assigned to a variable before initialization in Python, we have to specify the data type and structure of the array elements while creating the empty array.

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


1 Answers

You can do this:

newrow = [1, 2, 3] A = numpy.vstack([A, newrow]) 
like image 100
jknair Avatar answered Sep 23 '22 00:09

jknair