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 ;-)
You can use
numpy.append()
to append a row to numpty array and reshape to a matrix later on.I use 'np.vstack' which is faster, EX:
As this question is been 7 years before, in the latest version which I am using is numpy version 1.13, and python3, I am doing the same thing with adding a row to a matrix, remember to put a double bracket to the second argument, otherwise, it will raise dimension error. same usage in
np.r_
Just to someone's intersted, if you would like to add a column,
array = np.c_[A,np.zeros(#A's row size)]
well u can do this :
If you can do the construction in a single operation, then something like the vstack-with-fancy-indexing answer is a fine approach. But if your condition is more complicated or your rows come in on the fly, you may want to grow the array. In fact the numpythonic way to do something like this - dynamically grow an array - is to dynamically grow a list:
Lists are highly optimized for this kind of access pattern; you don't have convenient numpy multidimensional indexing while in list form, but for as long as you're appending it's hard to do better than a list of row arrays.
What is
X
? If it is a 2D-array, how can you then compare its row to a number:i < 3
?EDIT after OP's comment:
add to
A
all rows fromX
where the first element< 3
: