在python中连接numpy矩阵的所有行

use*_*386 6 python numpy

我有一个numpy矩阵,并希望将所有行连接在一起,所以我最终得到一个长数组.

#example

input:
[[1 2 3]
 [4 5 6}
 [7 8 9]]

output:
[[1 2 3 4 5 6 7 8 9]]
Run Code Online (Sandbox Code Playgroud)

我现在这样做的方式似乎并不像pythonic.我相信有更好的方法.

combined_x = x[0] 
for index, row in enumerate(x):
    if index!= 0:
        combined_x = np.concatenate((combined_x,x[index]),axis=1)
Run Code Online (Sandbox Code Playgroud)

感谢您的帮助.

sen*_*rle 7

我会建议ravel或者flatten方法ndarray.

>>> a = numpy.arange(9).reshape(3, 3)
>>> a.ravel()
array([0, 1, 2, 3, 4, 5, 6, 7, 8])
Run Code Online (Sandbox Code Playgroud)

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]])
Run Code Online (Sandbox Code Playgroud)

但是,如果你需要的副本,以避免内存共享如上图所示,你就要去使用更好的flattenconcatenate,因为你可以从这些时间看:

>>> %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
Run Code Online (Sandbox Code Playgroud)

另请注意,您可以获得输出所示的精确结果(一行二维数组)reshape(感谢Pierre GM!):

>>> 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
Run Code Online (Sandbox Code Playgroud)


Mae*_*ler 5

您可以使用 numpyconcatenate函数

>>> ar = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> np.concatenate(ar)
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
Run Code Online (Sandbox Code Playgroud)

你也可以尝试flatten

>>> ar.flatten()
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
Run Code Online (Sandbox Code Playgroud)