I have a numpy matrix and would like to concatenate all of 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 am doing it now doe not seem pythonic. I’m 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)
Thank you for the help.
I would suggest the
ravelorflattenmethod ofndarray.ravelis faster thanconcatenateandflattenbecause it doesn’t return a copy unless it has to:But if you need a copy to avoid the memory sharing illustrated above, you’re better off using
flattenthanconcatenate, as you can see from these timings:Note also that you can achieve the exact result that your output illustrates (a one-row 2-d array) with
reshape(thanks Pierre GM!):