如何向numpy数组添加行?
我有一个数组A:
A = array([[0, 1, 2], [0, 2, 0]])
如果X中每行的第一个元素满足特定条件,我希望将行从另一个数组X添加到此数组中。
Numpy数组没有像lists那样的“append”方法,至少看起来是这样。
如果A和X是列表,我只会这样做:
for i in X:
if i[0] < 3:
A.append(i)
有没有一种数字方法来做同样的事情?
谢谢,S ;-)
发布于 2010-10-07 20:14:03
什么是X
?如果它是一个2D数组,那么如何将其行与一个数字进行比较: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]])
将X
中第一个元素为< 3
的所有行添加到A
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]])
发布于 2010-10-07 20:15:51
您可以这样做:
newrow = [1, 2, 3]
A = numpy.vstack([A, newrow])
发布于 2018-03-04 00:40:43
如果每行之后都不需要计算,那么在python中添加行,然后转换为numpy会快得多。下面是使用python 3.6和numpy 1.14进行的定时测试,每次添加100行:
import numpy as np
from time import perf_counter, sleep
def time_it():
# Compare performance of two methods for adding rows to numpy array
py_array = [[0, 1, 2], [0, 2, 0]]
py_row = [4, 5, 6]
numpy_array = np.array(py_array)
numpy_row = np.array([4,5,6])
n_loops = 100
start_clock = perf_counter()
for count in range(0, n_loops):
numpy_array = np.vstack([numpy_array, numpy_row]) # 5.8 micros
duration = perf_counter() - start_clock
print('numpy 1.14 takes {:.3f} micros per row'.format(duration * 1e6 / n_loops))
start_clock = perf_counter()
for count in range(0, n_loops):
py_array.append(py_row) # .15 micros
numpy_array = np.array(py_array) # 43.9 micros
duration = perf_counter() - start_clock
print('python 3.6 takes {:.3f} micros per row'.format(duration * 1e6 / n_loops))
sleep(15)
#time_it() prints:
numpy 1.14 takes 5.971 micros per row
python 3.6 takes 0.694 micros per row
因此,对于七年前的原始问题,简单的解决方案是在将行转换为numpy数组后使用vstack()添加新行。但更现实的解决方案应该考虑到vstack在这些情况下的糟糕性能。如果不需要在每次加法后对数组运行数据分析,最好将新行缓冲到python行列表(实际上是列表列表),并在进行任何数据分析之前使用vstack()将它们作为一个组添加到numpy数组中。
https://stackoverflow.com/questions/3881453
复制相似问题