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

在python中连接numpy矩阵的所有行,python,numpy,Python,Numpy,我有一个numpy矩阵,我想把所有的行连接在一起,这样我就得到了一个长数组 #example input: [[1 2 3] [4 5 6} [7 8 9]] output: [[1 2 3 4 5 6 7 8 9]] 我现在做这件事的方式似乎不像蟒蛇。我相信有更好的办法 combined_x = x[0] for index, row in enumerate(x): if index!= 0: combined_x = np.concatenate((co

我有一个numpy矩阵,我想把所有的行连接在一起,这样我就得到了一个长数组

#example

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

output:
[[1 2 3 4 5 6 7 8 9]]
我现在做这件事的方式似乎不像蟒蛇。我相信有更好的办法

combined_x = x[0] 
for index, row in enumerate(x):
    if index!= 0:
        combined_x = np.concatenate((combined_x,x[index]),axis=1)
谢谢您的帮助。

您可以使用numpy:

您也可以尝试:

我建议使用
ndarray
的or方法

>>> a = numpy.arange(9).reshape(3, 3)
>>> a.ravel()
array([0, 1, 2, 3, 4, 5, 6, 7, 8])
ravel
concatenate
flant
更快,因为它不会返回副本,除非它必须:

>>> 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]])
但是,如果您需要一个副本来避免上述内存共享,那么最好使用
展平
而不是
串联
,从这些计时中可以看出:

>>> %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
还请注意,您可以通过
重塑
(谢谢!)获得输出所示的精确结果(一行二维阵列):


似乎正是用户想要的。@senderle--ravel也是我的第一直觉。请注意,
ravel
flatten
会将2D数组转换为1D数组,即从
(N,M)
转换为
(N*M,)
形状。OP可能需要添加
。重塑(1,-1)
以强制输出到2D数组(1行,多列)。当然,如果您只想将2D数组转换为1D数组,则速度越快的是
您的_数组。shape=-1
…@PierreGM,感谢您指出了输出中的差异。关于
your\u array.shape
——我做了一些非正式的计时,认为
your\u array.shape=-1,
your\u array.shape(-1,)
快一点——可能是因为后者创建了一个新视图。但有些令人惊讶的是,
your_-array.shape=-1
的速度是
your_-array.shape=(-1,)
的两倍。时间上的差异有点令人惊讶。使用
-1
(-1,)
是一种快捷方式。无论如何,我们可能应该使用
您的\u array.size
(您的\u array.size,)
跳过测试。。。
>>> 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]])
>>> %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
>>> 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