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

Time:10-30

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]

CodePudding user response:

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]

CodePudding user response:

If I understood correctly your question (and 4 other answers say I didn't), your problem is not how to flatten() or reshape(-1) an array, but how to ensure that even after reshaping, it still display with 4 elements per line.

I don't think you can, strictly speaking. Arrays are just a bunch of elements. They don't contain indication about how we want to see them. That's a printing problem, you are supposed to solve when printing. You can see here that people who want to do that... start with reshaping array in 2D.

That being said, without creating your own printing function, you can control how numpy display arrays, using np.set_printoptions.

Still, it is tricky so, because this function allows you only to specify how many characters, not elements, are printed per line. So you need to know how many chars each element will need, to force linebreaks.

In your example:

np.set_printoptions(formatter={"all":lambda x:"{:>6}".format(x)}, linewidth=7 (6 2)*4)

The formatter ensure that each number use 6 chars. The linewidth, taking into account "array([" part, and the closing "])" (9 chars) plus the 2 ", " between each elements, knowing we want 4 elements, must be 9 6×4 2×3: 9 chars for "array([...])", 6×4 for each 4 numbers, 2×3 for each 3 ", " separator. Or 7 (6 2)×4.

You can use it only for one printing

with np.printoptions(formatter={"all":lambda x:"{:>6}".format(x)}, linewidth=7 (6 2)*4):
    print(s.reshape(-1))

CodePudding user response:

you can use itertools.chain

from itertools import chain
import numpy as np
s=np.arange(12).reshape(3,4)
print(list(chain(*s)))
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
print(s.reshape(12,)) # this will also work
print(s.reshape(s.shape[0] * s.shape[1],)) # if don't know number of elements before hand

CodePudding user response:

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]
  • Related