Combining all rows of a numpy matrix in python

I have a numpy matrix and would like to combine all the rows together, so I end up with one long array.

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

The way I do it now does not seem pythonic. I am sure there is a better way.

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

Thanks for the help.

+6
source share
2 answers

I would suggest the ravel or flatten method.

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

ravel faster than concatenate and flatten because it does not return a copy if it does not matter:

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

But if you need a copy to avoid memory sharing, as shown above, you'd better use flatten than concatenate , as you can see from these timings:

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

Please also note that you can achieve the exact result that shows your output (single-row 2nd array) with reshape (thanks 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 
+7
source

You can use the numpy concatenate function:

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

You can also try flatten :

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

All Articles