Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reshape a 2D array into 1D in python?

Let me edit my question again. I know how flatten works but I am looking if it possible to remove the inside braces and just simple two outside braces just like in MATLAB and maintain the same shape of (3,4). here it is arrays inside array, and I want to have just one array so I can plot it easily also get the same results is it is in Matlab. For example I have the following matrix (which is arrays inside array):

s=np.arange(12).reshape(3,4)
print(s)
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

Is it possible to reshape or flatten() it and get results like this:

[ 0  1  2  3
  4  5  6  7
  8  9 10 11]

2 Answers

Try .ravel():

s = np.arange(12).reshape(3, 4)
print(s.ravel())

Prints:

[ 0  1  2  3  4  5  6  7  8  9 10 11]
like image 163
Andrej Kesely Avatar answered Jul 30 '26 21:07

Andrej Kesely


Simply, using reshape function with -1 as shape should do:

print(s)
print(s.reshape(-1))

[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
[ 0  1  2  3  4  5  6  7  8  9 10 11]
like image 28
drx Avatar answered Jul 30 '26 21:07

drx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!