Numpy - add row to array

2019-01-06 09:41发布

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 ;-)

8条回答
你好瞎i
2楼-- · 2019-01-06 10:02

You can use numpy.append() to append a row to numpty array and reshape to a matrix later on.

import numpy as np
a = np.array([1,2])
a = np.append(a, [3,4])
print a
# [1,2,3,4]
# in your example
A = [1,2]
for row in X:
    A = np.append(A, row)
查看更多
太酷不给撩
3楼-- · 2019-01-06 10:08

I use 'np.vstack' which is faster, EX:

import numpy as np

input_array=np.array([1,2,3])
new_row= np.array([4,5,6])

new_array=np.vstack([input_array, new_row])
查看更多
冷血范
4楼-- · 2019-01-06 10:09

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_

np.append([[1, 2, 3], [4, 5, 6]], [[7, 8, 9]], axis=0)
>> array([[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9]])

Just to someone's intersted, if you would like to add a column,

array = np.c_[A,np.zeros(#A's row size)]

查看更多
Animai°情兽
5楼-- · 2019-01-06 10:11

well u can do this :

  newrow = [1,2,3]
  A = numpy.vstack([A, newrow])
查看更多
一纸荒年 Trace。
6楼-- · 2019-01-06 10:19

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:

A = np.array([[1,2,3],[4,5,6]])
Alist = [r for r in A]
for i in range(100):
    newrow = np.arange(3)+i
    if i%5:
        Alist.append(newrow)
A = np.array(Alist)
del Alist

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.

查看更多
我想做一个坏孩纸
7楼-- · 2019-01-06 10:21

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:

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

add to A all rows from X where the first element < 3:

A = vstack((A, X[X[:,0] < 3]))

# returns: 
array([[0, 1, 2],
       [0, 2, 0],
       [0, 1, 2],
       [1, 2, 0],
       [2, 1, 2]])
查看更多
登录 后发表回答