Numpy - 将行添加到数组

问题描述:

如何将行添加到 numpy 数组中?

How does one add rows to a numpy array?

我有一个数组 A:

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

如果 X 中每一行的第一个元素满足特定条件,我希望从另一个数组 X 向该数组添加行.

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 数组没有像列表那样的追加"方法,或者看起来如此.

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

如果 A 和 X 是列表,我只会这样做:

If A and X were lists I would merely do:

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

是否有 numpythonic 方法来做等价的?

Is there a numpythonic way to do the equivalent?

谢谢,;-)

什么是 X?如果它是一个二维数组,那么你如何将它的行与一个数字进行比较: i ?

What is X? If it is a 2D-array, how can you then compare its row to a number: i < 3?

在 OP 评论后

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

添加到 A 来自 X 的所有行,其中第一个元素 :

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

import numpy as np
A = np.vstack((A, X[X[:,0] < 3]))

# returns: 
array([[0, 1, 2],
       [0, 2, 0],
       [0, 1, 2],
       [1, 2, 0],
       [2, 1, 2]])