python - 在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]]

我现在做这件事的方式看起来不像 pythonic。我相信有更好的方法。

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

谢谢你的帮助。

最佳答案

我会建议 ravelflatten ndarray 的方法。

>>> 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

关于python - 在python中连接一个numpy矩阵的所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13252781/

相关文章:

python - 检查是否填充了多行,如果没有填充所有值

python - 似乎同时安装了 NumPy 1.8.2 和 1.10.4,还有 rllab 和 OpenAI gym 之间的兼容性问题?

复合对象上的 python 垃圾收集器行为

python - 禁用 slider 中的箭头键

python - 如何从 CSV 的任意 BZ2 流中读取行?

Python,用格式化字符串替换所有数组值

python - 如何连接列表中的字符串对

python - Pysqlite 设置错误

python - numpy 在进行矩阵乘法时是否使用内存中的空间局部性?

python - 计算 PIL 逊相关系数