在Python中将numpy矩阵的所有行连接起来

7
我有一个numpy矩阵,想将所有行连接起来,以便得到一个长数组。
#example

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

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

我现在的做法似乎不太符合Pythonic的风格,我相信有更好的方法。

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

感谢您的帮助。

@senderle -- 我也觉得ravel是我的第一选择。发表为答案,我会很高兴地点赞。 - mgilson
2个回答

9

我建议使用ndarrayravelflatten方法。

你可以参考ravel方法文档flatten方法文档了解更多信息。

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

ravelconcatenateflatten更快,因为它只有在必要时才返回副本:

>>> 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而不是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

同时请注意,您可以使用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

1
请注意,ravelflatten将把您的二维数组转换为一维数组,即从(N,M)变为(N*M,)形状。 OP可能希望添加.reshape(1,-1)以强制输出为二维数组(1行,多列)。 - Pierre GM
当然,如果你只想将你的二维数组转换成一维数组,更快的方法是 your_array.shape = -1... - Pierre GM
@PierreGM,感谢您指出输出差异。关于 your_array.shape -- 我进行了更多非正式的计时,证明 your_array.shape = (-1,)your_array.reshape((-1,)) 稍微快一些 -- 可能是因为后者创建了一个新视图。但有点令人惊讶的是,your_array.shape = -1 的速度比 your_array.shape = (-1,) 慢了两倍。 - senderle
时间差有点令人惊讶。使用-1(-1,)只是一种快捷方式,我们应该使用your_array.size(your_array.size,)来跳过测试... - Pierre GM

6
您可以使用numpy的concatenate函数:concatenate函数文档
>>> 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])

您也可以尝试使用flatten函数:

>>> ar.flatten()
array([1, 2, 3, 4, 5, 6, 7, 8, 9])

似乎正是用户想要的。 - orlp

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接