我有一个 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)
谢谢你的帮助。
最佳答案
我会建议 ravel
或 flatten
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
而不是 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/