Numpy - 将行添加到数组 [英] Numpy - add row to array
本文介绍了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 <;3
?
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
的所有行,其中第一个元素 <3
:
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]])
这篇关于Numpy - 将行添加到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文