我会建议ravel
orflatten
的方法ndarray
。
>>> a = numpy.arange(9).reshape(3, 3)
>>> a.ravel()
array([0, 1, 2, 3, 4, 5, 6, 7, 8])
ravel
比它更快concatenate
,flatten
因为它不会返回副本,除非它必须:
>>> a.ravel()[5] = 99
>>> a
array([[ 0, 1, 2],
[ 3, 4, 99],
[ 6, 7, 8]])
>>> a.flatten()[5] = 77
>>> a
array([[ 0, 1, 2],
[ 3, 4, 99],
[ 6, 7, 8]])
但是如果你需要一个副本来避免上面说明的内存共享,你最好使用flatten
than concatenate
,从这些时间可以看出:
>>> %timeit a.ravel()
1000000 loops, best of 3: 468 ns per loop
>>> %timeit a.flatten()
1000000 loops, best of 3: 1.42 us per loop
>>> %timeit numpy.concatenate(a)
100000 loops, best of 3: 2.26 us per loop
另请注意,您可以使用(感谢 Pierre GM!)获得输出说明的确切结果(单行二维数组):reshape
>>> a = numpy.arange(9).reshape(3, 3)
>>> a.reshape(1, -1)
array([[0, 1, 2, 3, 4, 5, 6, 7, 8]])
>>> %timeit a.reshape(1, -1)
1000000 loops, best of 3: 736 ns per loop